Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach avoid naming conflicts for javascript functions in separate .js files?

Tags:

javascript

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

like image 704
ChrisP Avatar asked Aug 10 '09 20:08

ChrisP


People also ask

How to avoid JavaScript conflict?

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.


1 Answers

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/

like image 186
Chetan S Avatar answered Sep 20 '22 04:09

Chetan S