JavaScript 来自 class 扩展的函数无法识别
JavaScript function from class extension not recognized
我正在玩 classes ES6,遇到了以下代码的行为。
我得到的错误是 bob.personName is not a function
。
class 和它的扩展都定义了 constructor
但我仍然无法让它工作。我在我认为可能是问题所在的行下添加了评论。感谢您的帮助!
class Person {
constructor(canSpeak) {
this.canSpeak = true;
}
}
class Hello extends Person {
constructor(name) {
this.name = name;
}
personName() { //am I missing a parameter?
if (this.canSpeak) {
return `Name is: ${this.name}, can speak? ${this.canSpeak}`;
}
};
};
const bob = new Person('Bob'); //should I call Hello extension instead?
console.log(bob.personName());
由于方法存在于 Hello.prototype
,而不存在于 Person.prototype
,您需要实例属于 Hello
.
您也不能引用 this
,直到在子类的构造函数中调用 super
,所以在分配给 this.name
:
之前这样做
class Person {
constructor(canSpeak) {
this.canSpeak = true;
}
}
class Hello extends Person {
constructor(name) {
super();
this.name = name;
}
personName() { //am I missing a parameter?
if (this.canSpeak) {
return `Name is: ${this.name}, can speak? ${this.canSpeak}`;
}
};
};
const bob = new Hello('Bob'); //should I call Hello extension instead?
console.log(bob.personName());
我正在玩 classes ES6,遇到了以下代码的行为。
我得到的错误是 bob.personName is not a function
。
class 和它的扩展都定义了 constructor
但我仍然无法让它工作。我在我认为可能是问题所在的行下添加了评论。感谢您的帮助!
class Person {
constructor(canSpeak) {
this.canSpeak = true;
}
}
class Hello extends Person {
constructor(name) {
this.name = name;
}
personName() { //am I missing a parameter?
if (this.canSpeak) {
return `Name is: ${this.name}, can speak? ${this.canSpeak}`;
}
};
};
const bob = new Person('Bob'); //should I call Hello extension instead?
console.log(bob.personName());
由于方法存在于 Hello.prototype
,而不存在于 Person.prototype
,您需要实例属于 Hello
.
您也不能引用 this
,直到在子类的构造函数中调用 super
,所以在分配给 this.name
:
class Person {
constructor(canSpeak) {
this.canSpeak = true;
}
}
class Hello extends Person {
constructor(name) {
super();
this.name = name;
}
personName() { //am I missing a parameter?
if (this.canSpeak) {
return `Name is: ${this.name}, can speak? ${this.canSpeak}`;
}
};
};
const bob = new Hello('Bob'); //should I call Hello extension instead?
console.log(bob.personName());