javascript - 为什么 Javascript ES6 不能调用匿名超函数?
问题描述
请解释使用匿名函数和使用类函数的父子关系之间的区别?在案例 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.
解决方案
只有一个实例对象,一个对象上不能有两个同名的属性。您的子类属性会覆盖超类的属性。
此外,您不能通过super
assuper
引用上层原型访问属性,并且在您的第二种情况下不包含任何属性(在您的第一种情况下,它包含该方法)。因此,super.exec
isundefined
和调用它会引发错误。
原型链如下所示:
// 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
,但这是因为类字段是在一个特殊的初始化函数内部评估的,并且它具有Child
[[HomeObject]],而不是实例,并且super
引用[[HomeObject]]
s原型,会参考Parent
。
推荐阅读
- reactjs - 为什么 Axios For Loop 不允许我在 React 中操作数据?
- kubernetes - GKE 上的 CI CD 管道 - 推送清单失败(已完成步骤 #5 -“推送清单”错误)
- c# - Xamarin.Android Tap Gesture 和 Long Press Gesture 不能一起工作
- wso2 - 提出请求未到达后端 api
- c++ - 是否有预处理器方法可以从调试符号中删除代码段?
- vba - 格式 - 预期的数组
- r - 使用 scale_fill_gradientn 将特定颜色分配给条形图中的确定值
- ios - Xcode 11.2 场景编辑器是否允许添加组件?
- excel - Excel VBA 从域中获取 IP 地址
- reactjs - 浅渲染返回空对象,wrapper.debug() 显示完全渲染的组件