0

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

MySpace = {

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

现在想象一下,我有大约 12K 行 JavaScript,而不是几行代码,其中包含数百个函数和大约 60 个全局变量。我已经知道如何将我的代码转换为命名空间,但我想知道是否有比减少 12K 行代码并到处添加更快的方法MySpace.

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

4

2 回答 2

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 演示

于 2012-08-07T15:05:47.143 回答
0

function主体包裹在现有代码周围以用作范围,从全局隐藏所有内容 - 这将允许您进行内部调用而无需Namespace.在任何地方粘贴前缀,巧妙地隐藏您不希望其他人看到的内容,并且也需要最少的更改.

之后,决定你想为每个人“导出”哪些功能,并将它们分配给你想用作“命名空间”的对象的属性。

于 2012-08-07T15:22:16.913 回答