我们有2个单身人士:
let Singleton = (() => {
let instance;
function init() {
return instance || (instance = this);
}
return init;
})();
let s = new Singleton();
let s2 = new Singleton();
console.log(s == s2);
let Singleton2 = (() => {
let instance;
let init = () => {
return instance || (instance = this);
}
return init;
})();
let s1 = new Singleton2();
let s12 = new Singleton2();
console.log(s1 == s12);
第一个像它想象的那样工作,但第二个给我: 未捕获的TypeError:Singleton2不是构造函数
有些人可以告诉我为什么第二个Singleton不是构造函数吗? 谢谢你的时间。
答案 0 :(得分:0)
这是因为您在第二个上使用了Arrow function。它以不同的方式对待this
。
箭头函数表达式的语法短于函数表达式,并且没有自己的this,arguments,super或new.target。这些函数表达式最适合非方法函数,不能用作构造函数。