名前空間をそのようにまとめるのが好きです。柔軟性は非常に高く、必要に応じて、MySpace名前空間のさまざまなモジュールを別々のラッパーに分けることもできます。それでも、すべての前に何らかの_self.
参照を追加する必要がありますが、少なくともこの方法では、必要に応じて名前空間の名前全体を非常にすばやく変更できます。
このメソッドを使用して、最初のモジュールから_self.anotherFunc()を呼び出すこともでき、2番目のモジュールに到達する方法を確認できます。
(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デモ