Possible Duplicate:
Simplest/Cleanest way to implement singleton in JavaScript?的Javascript:最好Singleton模式
我用这个模式来单身,本例中的单是地球脉动:
var NAMESPACE = function() {
var privateFunction1 = function() {
privateFunction2();
};
var privateFunction2 = function() {
alert('I\'m private!');
};
var Constructors = {};
Constructors.PlanetEarth = function() {
privateFunction1();
privateFunction2();
};
Constructors.PlanetEarth.prototype = {
someMethod: function() {
if (console && console.log) {
console.log('some method');
}
}
};
Constructors.Person = function (name, address) {
this.name = name;
this.address = address;
};
Constructors.Person.prototype = {
walk: function() {
alert('STOMP!');
}
};
return {
Person: Constructors.Person, // there can be many
PlanetEarth: new Constructors.PlanetEarth() // there can only be one!
};
}();
由于地球脉动的构造保持私密,也只能是一个。
现在,有人告诉我,这种自制的东西并不是最好的,主要是因为我没有学历教育,而且我倾向于用愚蠢的方式解决问题。你会提出什么样的更好替代我的方法,其中更好被定义为风格上更好和/或更强大?
如果这是包含在页面上两次,最新的对象将覆盖前面的。实际上,它发生 - 有时会产生意想不到的后果。单身封闭模式可以阻止这种情况所以,如果你发布一个脚本/库,它将优雅地处理其他使用它的人的滥用。正因如此,大部分Google的API库都这样做。假设我在网站上使用Google地图,但希望通过一些第三方来安装widget,其中也明确包含地图库。我是否需要更改第三方代码,或者库本身是否应该优雅地处理这个问题? – defines 2013-04-17 14:36:05
如果你使用:var earth = earth || {....}; – chees 2013-09-13 13:01:21
如果您使用的是正确的文件管理器,如requirejs,它也不会覆盖它。 – mwilcox 2013-09-25 22:19:46