请说明使用匿名函数使用父子关系与使用类函数之间的区别吗? 在情况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.
答案 0 :(得分:0)
只有一个实例对象,并且在一个对象上不能有两个具有相同名称的属性。您的子类属性将覆盖超类的属性。
另外,您无法通过super
访问属性,因为super
指的是上层原型,并且在第二种情况下(在您的第二种情况下,第一种情况包含方法)。因此,super.exec
是undefined
,并且调用会引发错误。
原型链如下所示:
// Case 1
- super ------------v
{ name: "ChildName", age: 31 } -> Child { exec() { ... } } -> Parent { exec() { ... } }
// Case 2
- super² --------------------v
{ name: "ChildName", age: 31, exec() { ... } } -> Child {} -> Parent {}
²实例内部的super
指向Parent
可能有点令人困惑,但这是因为类字段是evaluated inside of a special initializer function,并且它的实名是Child
[[HomeObject]],而不是实例,作为super
refers to the [[HomeObject]]
s prototype,它将引用Parent
。