在命名空间中封装javascript

时间:2012-08-07 14:52:27

标签: javascript

我希望将javascript封装在这样的命名空间中:

MySpace = {

   SomeGlobal : 1,
   A: function () { ... }, 
   B: function () { ....; MySpace.A(); .... },
   C: function () { MySpace.SomeGlobal = 2;.... }
}

现在想象一下,代替几行代码,我有大约12K行的javascript,有数百个函数和大约60个全局变量。我已经知道如何将我的代码转换为命名空间,但我想知道是否有更快的方法来执行此操作,而不是使用12K行代码并在整个地方添加MySpace.

如果有更快的方法,请告诉我。 谢谢你的建议。

2 个答案:

答案 0 :(得分:1)

我喜欢像这样包装命名空间。灵活性是巨大的,如果我们想要的话,我们甚至可以在单独的包装器中分离MySpace命名空间的不同模块。您仍然需要在所有内容之前添加某种_self.引用,但至少在这种情况下,如果需要,您可以非常快速地更改命名空间的整个名称。

你可以看到这个方法如何从第一个模块调用_self.anotherFunc(),你将进入第二个模块。

(function (MySpace, $, undefined) {

    var _self = MySpace; // create a self-reference
    _self.test = function () { 
        alert('we got here!'); 
        _self.anotherFunc(); // testing to see if we can get the 2nd module
    };

    _self = MySpace; // reassign everything just incase

}(window.MySpace = window.MySpace || {}, jQuery));

$(function () { 

    MySpace.test(); // call module 1
    MySpace.callOtherModule(); // call module 2

});

// Here we will create a seperate Module to the MySpace namespace
(function (MySpace, $, undefined) {
    var _self = MySpace; // create a self-reference

    _self.callOtherModule = function () {
        alert('we called the 2nd module!');    
    };

    _self.anotherFunc = function () { 
        alert('We got to anotherFunc from the first module, even by using _self.anotherFunc()!'); 
    };
    _self = MySpace; // reassign everything just incase

}(window.MySpace = window.MySpace || {}, jQuery));​

jsFiddle DEMO

答案 1 :(得分:0)

围绕现有代码包裹function正文作为范围,隐藏全局的所有内容 - 这样您就可以进行内部调用,而不会在任何地方粘贴Namespace.前缀,整齐地隐藏您不使用的内容希望其他人都能看到,并且也需要很少的更改。

之后,确定要为每个人“导出”哪些函数,并将它们分配给要用作“命名空间”的对象属性。

相关问题