将 JavaScript 封装在命名空间中

encapsulating javascript inside a namespace

本文关键字:命名空间 封装 JavaScript      更新时间:2023-09-26

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

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

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

请让我知道是否有更快的方法可以做到这一点。感谢您的建议。

我喜欢这样包装命名空间。灵活性是巨大的,如果我们愿意,我们甚至可以在单独的包装器中分离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));​

js小提琴演示

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

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