【发布时间】:2015-05-14 15:53:14
【问题描述】:
在什么场景下我们需要在javascript中实现Singleton Class如下
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
function run() {
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert("Same instance? " + (instance1 === instance2));
}
【问题讨论】:
-
何时需要一个实例?
-
控制在其环境中需要或应该是唯一的任何资源。例如。库、覆盖的绘图画布、特定的解析器 ...
标签: javascript