gpt4 book ai didi

javascript - 访问 ES6 super 属性

转载 作者:可可西里 更新时间:2023-11-01 02:39:24 26 4
gpt4 key购买 nike

当我看到一些令人惊讶的东西时,我正在摆弄 ES6 类:

class Animal {
constructor(name) {
this.name = name;
}
speak(sound) {
console.log(sound);
}
}

class Dog extends Animal {
constructor(name, age) {
super(name);
this.age = age;
}
speak() {
super.speak("Woof! I'm " + super.name + " and am " + this.age);
}
}

然后,我创造了我的狗:

var mydog = new Dog("mydog",3);
mydog.speak();

现在打印

Woof! I'm undefined and am 3

所以我的问题是,为什么 super.name 未定义?在这种情况下,我希望它是 mydog

最佳答案

this在父构造函数中仍然引用狗,所以this.name = name , 设置属性 name直接在Dog对象而不是其父对象。使用 this.name将工作:

super.speak("Woof! I'm " + this.name + " and am " + this.age);

关于javascript - 访问 ES6 super 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34517071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com