我喜欢这样包装命名空间。灵活性是巨大的,如果我们愿意,我们甚至可以将 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 演示