<分区>
在当前使用 ES6 类语法和 get/set 语法的 JavaScript 项目中,我偶然发现了一个我无法解释的行为。
首先,一个按预期工作的提取演示:
class A {
constructor() {
this.__value = null;
}
get value() {
return this.__value;
}
set value(value) {
this.__value = value;
}
}
class B extends A { }
let b = new B();
b.value = 2;
console.log(b.value); // output: 2
设置和获取 b.value(在 A.prototype 中定义)有效。
现在考虑以下演示,其中我仅将 setter 从 A 移动到 B:
class A {
constructor() {
this.__value = null;
}
get value() {
return this.__value;
}
}
class B extends A {
set value(value) {
this.__value = value;
}
}
let b = new B();
b.value = 2; // b.__value is 2
console.log(b.value); // output: undefined
设置 value 有效(因为 b.__value 确实是 2),但是 getter 似乎不存在,尽管它仍然在 A.prototype 中定义。
这里有什么问题?