先上代码
class Singleton {
constructor(data) {
if (Singleton.prototype.Instance === undefined) {
this.data = data;
Singleton.prototype.Instance = this;
}
return Singleton.prototype.Instance;
}
}
let ob1 = new Singleton("one");
let ob2 = new Singleton("two");
let ob3 = new Singleton("Three");
ob2.init = 'Object flg';
console.log(ob1 === ob2); // => true
console.log(ob1 === ob3); // => true
console.log(ob1);
/* =>
{
data:"one",
init:"Object flg",
__proto__:Object
}
*/
console.log(ob2);
/* =>
{
data:"one",
init:"Object flg",
__proto__:Object
}
*/
console.log(ob3);
/* =>
{
data:"one",
init:"Object flg",
__proto__:Object
}
*/
代码解释:
-
prototype
和__proto__
的关系
对象的__proto__
就是构造函数的protoype
。
此两者都是一个对象。 - 什么是单例模式
保证一个类仅有一个实例。
修改该实例,自然会影响到其它的实例引用。