如何在不污染全局命名空间的情况下共享常用的jquery函数?

时间:2013-12-04 20:20:24

标签: javascript jquery scope

假设我有这些文件:a.js b.js c.js,每个文件的定义如下:

(function(){
     function afunction() {
     }

     function yetanotherfunction() {
     }
... ...
})();

我还有一个名为common.js的文件,其中包含可以由倍数共享的函数:

function commonFunction() {
}

function yetAnotherCommonFunction() {
} 

我想将commonFunction,而另一个CommonMunctionFunction放在范围内。即:

(function() {
... //commonFunction, yetAnotherCommonFunction goes here
})();

但是,如果我这样做,我将无法从/ b / c.js范围调用常用函数。有没有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:4)

命名空间:

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

    Common.commonFunction = function() {
    }

    return Common;
}())

Common.commonFunction() // do something from anywhere

答案 1 :(得分:0)

您可以为每个脚本创建命名空间。执行此操作的简单脚本是使用如下命名空间脚本:

var ns = function (namespace, callback) {
   var nssplit = namespace.split('.'), x, curObj = window, curPos = null, lasObj;

   for (x = 0 ; x < nssplit.length ; x++) {
      curPos = nssplit[x];      
      if (curObj[curPos] === undefined) {
         curObj[curPos] = {};
      }
      lasObj = curObj;
      curObj = curObj[curPos];
   }
   lasObj[curPos] = callback;
};

ns('local.test', function() {
   document.getElementById('test').innerHTML = "test";
});

local.test();

您可以在此处查看http://jsfiddle.net/Nemesis02/Qtq8Q/