[英]Javascript: Using super to call parent prototype function inside child prototype function
我有一個關於原型和在 JS 中使用 super 的問題。
我有一個父母 class Person
。 我已經將一個新的toString()
function 連接到Person.prototype
。
然后,我有一個孩子 class Teacher
(擴展Person
)。 我也在嘗試覆蓋其原型上的toString()
方法,但是我想重用其父級的toString()
方法的結果。
我試圖在Teacher
function中調用super
object的toString()
方法,但是我得到一個錯誤,說super
是未定義的。 這是為什么? 是否可以在超級孩子的原型function中通過超級重用父母的方法?
現在,我知道這個問題可以通過另一種方式解決,但我仍然很好奇它是否可以通過上述方式實現。
這是一些參考代碼:
class Person {
name;
email;
constructor(name, email){
this.name = name;
}
}
Person.prototype.toString = function(){
return `name: ${this.name}`
}
class Teacher extends Person{
constructor(name, subject){
super(name);
this.subject = subject;
}
}
Teacher.prototype.toString = function(){
return this.super.toString() + ` subject: ${this.subject}`
}
let teacher = new Teacher("testname", "testSubject");
console.log(teacher.toString());
當您在這樣的原型上定義 function 時,我不相信super
可用。 相反,您應該在 class 中定義您的方法並使用super.toString
。 像這樣:
class Person { constructor(name, email) { this.name = name; } toString() { // you were missing `this` here return `name: ${this.name}`; } } class Teacher extends Person { constructor(name, subject) { super(name); this.subject = subject; } toString() { return super.toString() + ` subject: ${this.subject}`; } } let teacher = new Teacher("testname", "testSubject"); console.log(teacher.toString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.