我寫JavaScript的單例類,並希望使用Singleton模式是這樣的:JavaScript的單 - 這是正確的
function TestClass() {
var self = TestClass.prototype;
if (self.instance) return self.instance;
self.instance = this;
//methods and props declarations
}
var x = new TestClass;
var y = new TestClass;
console.log(x === y); // true
這似乎爲我想像的要工作,但我擔心內存泄漏。所以我決定詢問專家,如果這是正確的解決方案
你想要http://codereview.stackexchange.com/ – Andy
'new'關鍵字創建一個新的實例,所以你不在這裏創建一個單例 – Ibu
This thread http://stackoverflow.com/questions/1895635/javascript -singleton-question有一些很好的解決方案 –