【发布时间】:2019-08-19 14:57:03
【问题描述】:
请解释一下使用匿名函数的父子关系和使用类函数的区别? 在案例 1 中,一切都按预期工作。在情况 2 中,codepen 不返回任何结果。
//CASE 1
class Parent {
constructor(name) {
this.name = name;
}
exec() {
console.log('name', this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
exec() {
super.exec();
console.log('age', this.age);
}
}
const c = new Child('ChildName', 31);
c.exec();
//writes Childname + 31 (expected behaviour)
和
//CASE 2
class Parent {
constructor(name) {
this.name = name;
}
exec = () => {
console.log('name', this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
exec = () => {
super.exec();
console.log('age', this.age);
}
}
const c = new Child('ChildName', 31);
c.exec();
//writes nothing. Seems to crash.
【问题讨论】:
-
如果你没有使用像 babel 之类的转译器,那么你目前正在做的事情将会失败,因为类属性 ATM 不能是箭头函数。只是尚未实施。
-
@kemicofa 会抛出一个 SyntaxError 虽然 ...
-
@kemicofa:我在我的主项目中使用 babel。也在 codepen 上使用 babel。
-
@JonasWilms 我正在 codepen 中测试这个。浏览器不会冻结,但不会产生结果(我假设 codepen 不想编译)
标签: javascript ecmascript-6 babeljs anonymous-function es6-class