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
2 Answers
Reset to default 7If 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() {};