自問自答,
現在暫時使用getter/setter + scope變數來實作
「可在所有實例間分享」、「可繼承」的資料屬性。
"use strict";
let someHash = {
a:1,
b:2
};
class A {
get someHash() {
return someHash;
}
set someHash(value) {
someHash = value;
}
}
const a = new A();
const b = new A();
a.someHash.a = 2;
console.log(b.someHash.a); //2
但這樣的做法會讓對實例或者繼承者實例覆寫屬性時也蓋掉所有實例的屬性
a.someHash = {
c: 3
};
console.log(b.someHash.a); //undefined
要防止這點只要不設setter(讓嘗試寫入時出錯)或讓setter時不改變someHash即可,
要完整實作舊版prototype的機制大概得動用__偽private屬性
let someHash = {
a:1,
b:2
};
class A {
get someHash() {
return this.__someHash || someHash;
}
set someHash(value) {
this.__someHash = value;
}
}
const a = new A();
const b = new A();
a.someHash.a = 2;
console.log(b.someHash.a); //2
a.someHash = {
c: 3
};
console.log(a.someHash.a); //undefined
console.log(a.someHash.c); //3
console.log(b.someHash.a); //2