Is there a preferred approach to isolating functions in a .js file from potential conflicts with other .js files on a page due to similar names?
For example if you have a function
function AddTag(){}
in Core.js and then there is a
function AddTag(){}
in Orders.js they would conflict. How would you best structure your .js files and what naming conventions would you use to isolate them?
Thanks
Thus, if you are using another JavaScript library that uses the $ variable, you can run into conflicts with jQuery. In order to avoid these conflicts, you need to put jQuery in no-conflict mode immediately after it is loaded onto the page and before you attempt to use jQuery in your page.
You can use 'namespacing'. Like this
File1.js:
var Orders = {}
(function(o) {
o.function1 = function() {}
o.function2 = function() {}
})(Orders);
File2.js
var Sales = {}
(function(o) {
o.function1 = function() {}
o.function2 = function() {}
})(Sales);
You can invoke them like this:
Sales.function1();
Orders.function1();
In general do not use global functions/variables. Read about javascript module pattern here http://yuiblog.com/blog/2007/06/12/module-pattern/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With