请参考以下小提琴:http://jsfiddle.net/hBvSZ/5/
var NewObject = function () {
//Singleton should be accessible here
this.method1 = function() { }
};
此外,我们是否可以通过这样一种方式传递singleton,即singleton的方法只能由NewObject访问?
将单例存储在一个变量中:
var singleton;
function NewObject () {
if (typeof singleton == 'undefined') {
// initialize new object here.
}
}
这是基本的想法。
为了避免全局命名空间污染,可以使用闭包:
var NewObject = (function(){
var singleton;
return function () {
if (typeof singleton == 'undefined') {
// initialize new object here.
}
}
})();
尽管我怀疑你是否真的需要JavaScript中的Singleton模式,但我会这样做:
var Client = (function() {
var instance;
var Client = function() {
};
Client.prototype.hello = function() {
console.log("hello");
};
return {
getInstance: function() {
if (!instance) {
instance = new Client();
}
return instance;
},
otherHelper: function() {
console.log("look i'm helping!");
},
};
})();
var a = Client.getInstance();
var b = Client.getInstance();
a.hello(); // "hello"
b.hello(); // "hello"
console.log("a === b", a === b); // true
Client.otherHelper(); // look i'm helping!
如果你使用这个服务器端(例如node.js),你可以做这个
// client.js
var instance;
var getInstance = function getInstance() {
if (!instance) {
instance = new Client();
}
return instance;
};
var Client = function Client() {
};
Client.prototype.hello = function() {
console.log("hello");
};
exports.getInstance = getInstance;
然后使用简单的
// app.js
var Client = require("./client");
var myClient = Client.getInstance();