问题描述
我想知道以下是否符合ES6规范:
I'm wondering if the following is in compliance with the ES6 spec:
class X {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(name) {
this._name = name + "X";
}
}
class Y extends X {
constructor(name) {
super(name);
}
set name(name) {
super.name = name;
this._name += "Y";
}
}
想法是让y =新Y(); y.name =hi
应该导致 y.name ===hiXY
为真。
据我所知,这在启用了ES6标志的Chrome中不起作用。使用Babel和 es2015
标志也无效。在继承的setter中使用 super.name = ...
而不是ES6规范的一部分?或者这是Babel实现中的一个错误?
As far as I can tell, this doesn't work in Chrome with the ES6 flag turned on. It also doesn't work using Babel with the es2015
flag. Is using super.name = ...
in an inherited setter not part of the ES6 spec? Or is this a bug in the implementation of Babel?
推荐答案
class Y extends X {
constructor(name) {
super(name);
}
set name(name) {
super.name = name;
this._name += "Y";
}
}
将覆盖名称
正确使用的访问器 setter,没有getter。这意味着您的 y.name ===hiXY
将失败,因为 y.name
将返回 undefined
因为 name
没有getter。你需要:
will override the name
properly with an accessor for just the setter, with no getter. That means your y.name === "hiXY"
will fail because y.name
will return undefined
because there is no getter for name
. You need:
class Y extends X {
constructor(name) {
super(name);
}
get name(){
return super.name;
}
set name(name) {
super.name = name;
this._name += "Y";
}
}
这篇关于是否可以在ES6继承的类中调用超级setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!