自问自答,
现在暂时使用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