最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Avoid conflicts with function naming conventions javascript - Stack Overflow

programmeradmin2浏览0评论

I have a bunch of functions in my script which resides in a .js file. How can avoid conflicts with the names of my functions within the same page if some other script written by some other guys use the same function names as in my script ?

Is there a way to do this?

I have a bunch of functions in my script which resides in a .js file. How can avoid conflicts with the names of my functions within the same page if some other script written by some other guys use the same function names as in my script ?

Is there a way to do this?

Share Improve this question asked Apr 9, 2013 at 10:03 Claudio FerraroClaudio Ferraro 4,7316 gold badges49 silver badges83 bronze badges 1
  • u cannot avoid it pletely, but if u wrap in inside a class that will much of sense – ManMohan Vyas Commented Apr 9, 2013 at 10:05
Add a ment  | 

2 Answers 2

Reset to default 7

If you don't need access to those functions outside of your script you can wrap the whole script in an immediately invoked function expression:

(function () {
    // Your code here
}());

This introduces a new scope, so any declarations within it are not visible outside of it.

If you do need access outside of that scope, expose your functions as methods of a "namespace":

var YourStuff = (function () {
    // Private functions etc...

    // Expose public methods
    return {
        someMethod: function () {}
    };
}());

By taking this approach you only introduce a single global identifier, reducing the chances of a conflict. You can call the method as follows:

YourStuff.someMethod();

Use namespaces..

var pany = {};

pany.doSomething = function() {
};

pany.project = {};
pany.project.submodule = {};
pany.project.submodule.doSomething = function() {};
发布评论

评论列表(0)

  1. 暂无评论