Re: [问题] ES2015的class问题

楼主: mrbigmouth (大嘴先生)   2015-10-30 10:07:20
自问自答,
现在暂时使用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
作者: bibo9901 (function(){})()   2015-10-30 11:52:00
干嘛不直接放在prototype上就好
楼主: mrbigmouth (大嘴先生)   2015-10-30 11:57:00
我上篇有说啊 node.js下的class没有prototype让你改是babel编译时用prototype实作你才能改啊 我错了 原来只是不能直接设定 但是可以加属性

Links booklink

Contact Us: admin [ a t ] ucptt.com