先上代碼
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__
的關(guān)系
對(duì)象的__proto__
就是構(gòu)造函數(shù)的protoype
塑荒。
此兩者都是一個(gè)對(duì)象绿聘。 - 什么是單例模式
保證一個(gè)類僅有一個(gè)實(shí)例士飒。
修改該實(shí)例谬莹,自然會(huì)影響到其它的實(shí)例引用陋率。