我正在关注这篇文章。我理解单例模式是什么,但我无法理解代码。
let Singleton = (function(){
let instance = null;
function createInstance() {
let obj = new Object("I am the new instance");
return obj;
}
return {
getInstance:function() {
console.log(instance);
if(instance === null) {
instance = createInstance();
}
return instance;
}
}
})();
function test() {
let instance1 = Singleton.getInstance();
let instance2 = Singleton.getInstance();
console.log(Object.is(instance1,instance2));
}
test();
为什么 instance1 和 instance2 是一样的,每当我们调用时,我们总是将实例初始化为nullSingleton
。
每当我们调用时,我们总是将实例初始化为 null
Singleton
。
你不。Singleton
是return
语句中的对象,不包括语句let instance = null
。该语句只执行一次;这个变量是下捕获封闭在getInstance
返回对象的方法(Singleton.getInstance
)。代码等价于
let instance = null;
function createInstance() {
let obj = new Object("I am the new instance");
return obj;
}
let Singleton = {
getInstance: function() {
console.log(instance);
if (instance === null) {
instance = createInstance();
}
return instance;
}
}
除此之外,instance
和createInstance
隐藏在IIFE的范围内。
您可以let instance = null
通过插入更多日志语句来验证执行了多少次(以及何时)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句