开发者

Duplicate JavaScript names. Is it bad to have them?

As several developers work on the javascript files , many of them ended up writing the same file names again and again

simple example can be getCookie , setCookie type of functions.

Now we are doing aggregation on javascript files , will there be any problem if have same functions twice.

Right now things are working fine , but I want to kn开发者_如何学编程ow

Appreciate your help


Yes, there will definitely be a problem if you end up having a function unintentionally defined twice in the global namespace. The function that was last defined will simply overwrite the previous one.

You may want to consider using namespaces to tackle this problem. JavaScript namespaces are normally mimicked by using objects and closures, and often initialized with a self-invoking function:

var myNamespace = (function () {
   var _name = 'Bob';

   return {
      somePublicMethod: function () {
         return 'Hello, ' + _name;
      }
   };
})();

alert(myNamespace.somePublicMethod());


It's kind of like The Highlander — for any given global symbol, there can be only one!


Namespaces are part of the answer, the other part is not writing duplicate code.

The name of a function or variable should describe its purpose, so two functions with the same name should be the same function! You can't do this perfectly, of course, that's why we have namespaces.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜