最好的实现:
var langzi = window.langzi || {};
langzi.singleton = window.langzi.singleton || (function () {
var instance = null;
var constructor = function () {
return {
id: 1,
name: "test",
getMessage: function () {
console.log("id:" + this.id + ", name:" + this.name);
}
};
};
return {
getInstance: function () {
if (instance == null) {
instance = constructor();
}
return instance;
}
};
} ());
langzi.singleton = window.langzi.singleton || (function () {
var instance = null;
var constructor = function () {
return {
id: 1,
name: "test",
getMessage: function () {
console.log("id:" + this.id + ", name:" + this.name);
}
};
};
return {
getInstance: function () {
if (instance == null) {
instance = constructor();
}
return instance;
}
};
} ());
测试代码如下:
// test
var s1 = langzi.singleton.getInstance();
var s2 = langzi.singleton.getInstance();
s1.getMessage();
s2.getMessage();
console.log(s1 == s2);
var s1 = langzi.singleton.getInstance();
var s2 = langzi.singleton.getInstance();
s1.getMessage();
s2.getMessage();
console.log(s1 == s2);
按照Pro Javascript Design Pattern作者的说法,namespace都是singleton的应用。从广义来说,个人认为确实是的,但既然说到singleton,我觉得应该还是我上面的例子最具有代表性。