tags:

views:

214

answers:

3

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

+10  A: 

I limit the scope of the function to that file.

(function () {
    var AddTag = function AddTag () {
    };
}());

… and sometimes make some functions in it available to the global scope:

var thisNamespace = function () {
    var AddTag = function AddTag () {
        …
    };
    var foo = function foo() {
        AddTag();
        …
    };
    var bar = function bar() {
        …
    };
    return {
        foo: foo,
        bar: bar
    }
}();
David Dorward
So how would you call the function in your first example? Does the call have to be w/in the outer function? In addition, if one is using the jQuery $(document).ready(function() {}); can you call these functions, e.g., AddTag() from within that function? Is the outer function inside $(document).ready(), separate, or contained w/in it?
ChrisP
AddTag();. Yes. Yes — so long as the call is within the function limiting the scope. It is a function inside the anonymous function I wrote (just like AddTag).
David Dorward
Thanks. When I moved the jQuery $(document).ready... inside(function () {}());I can call the private functions.Thanks
ChrisP
A: 

use encapsulation (http://www.devx.com/gethelpon/10MinuteSolution/16467 and http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-javascript/)

in fileA.js

function fileA()
{
  this.function1 = function()
  {
    return 'foo';
  };

}

in fileB.js

function fileB()
{
  this.function1 = function()
  {
    return 'bar';
  };

}
Nir Levy
+1  A: 

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/

Chetan Sastry
Technically the function calls you show above are not necessary. Where they would be useful is if you had local variables you did not want to pollute the global namespace, since Javascript has function scope.
Jason S
Yes, but it is useful if you had long namespaces (such as the ones Yahoo uses). It saves you from typing `This.Is.A.Long.Namespace` every time you define a new function. You could just do `o.newFunction = function() {}`
Chetan Sastry