作为 Javascript 设计模式的新手,我遇到了模块模式,但我没有得到命名空间的东西。
在Addy Osmani 的关于 JS 设计模式的在线书籍的命名空间部分中,Addy 解释了这 5 种检查变量/命名空间存在的方法:
// This doesn't check for existence of "myApplication" in
// the global namespace. Bad practice as we can easily
// clobber an existing variable/namespace with the same name
var myApplication = {};
// The following options *do* check for variable/namespace existence.
// If already defined, we use that instance, otherwise we assign a new
// object literal to myApplication.
//
// Option 1: var myApplication = myApplication || {};
// Option 2 if( !MyApplication ){ MyApplication = {} };
// Option 3: window.myApplication || ( window.myApplication = {} );
// Option 4: var myApplication = $.fn.myApplication = function() {};
// Option 5: var myApplication = myApplication === undefined ? {} : myApplication;
我真正不明白的是它如何解决命名问题。
假设在我的代码尝试使用 myApplication 之前设置了 myApplication。例如,使用选项 1(或实际上是所有选项),如果 myApplication 已经在使用中,似乎不会改变任何东西,但只会覆盖 myApplication 的先前值:
// Higher in some script, where I don't know about it
var myApplication = 'whatever string or object used by the script';
// A bit of code later, where I come with my little Module Pattern
var myApplication = myApplication || {}; // Using Option 1
myApplication = (function($) {
var myAppVariable = 'blabla';
var myAppFunction = function() {
// Doing a few things here
};
return myAppFunction;
}) (jQuery);
// Using the module
myApplication.myAppFunction();
对我来说,这很令人困惑,因为我看不出它如何阻止我也踩到别人的脚趾。