Reputation: 50742
What are the ways to avoid variable/function conflicts in Javascript (without using jQuery plugins) ? I want to create my own new functions, but want to avoid conflicts.
I think using function scope (functions just for the purpose of scope) is one way. What are the other possibilities?
Also when you wrap your function in something to avoid conflicts, how do you actually access it from outside ?
I am looking for basic examples.
Upvotes: 0
Views: 995
Reputation: 147403
If you are only attaching methods to other objects that will call them, you can wrap your code in an immediately invoked function expression (IIFE) to assign the methods without creating any new global objects or properties. This strategy is useful for attaching listeners, where variables are shared using a closure to the execution context of the IIFE rather than the global context and since they are attached to objects that already exist in the execution context, there may be no additional global objects or variables.
Such functions still have access to global functions though.
A second strategy is to create a single named object and attach all your methods to that as properties. You can also share values as properties of the object or by closures within functions assigned by IIFEs.
In practice, a suitably chosen random prefix on all your global variables is just as good for avoiding name collisions, but it's not popular.
Upvotes: 1