gpt4 book ai didi

javascript - ES6 javascript继承

转载 作者:行者123 更新时间:2023-11-29 17:48:16 25 4
gpt4 key购买 nike

提供以下代码:

class Person {
constructor(name) {
this.name = name;
}
sayHello() {
console.log('Hello, my name is ' + this.name);
}
sayHelloAndBy() {
this.sayHello();
console.log('Bye');
}

}
class Student extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
sayHello() {
console.log(`Hi, I'm a studend and my name is ` + this.name);
}
}


let b = new Student("Some guy", 5);

b.sayHelloAndBy();

我想找出一种调用 sayHello 的方法,如 Person 中定义的那样,而不是在 Student 中定义。可能吗?

在 php 中有 self:: 允许这样做,但我不确定 JS 是否有类似的概念。

最佳答案

您可以通过 Person 的原型(prototype)属性引用 Person 中定义的 sayHello 版本,并使用必要的 调用它这使用Function#call :

sayHelloAndBye() {
Person.prototype.sayHello.call(this);
console.log('Bye');
}

可运行:

class Person {
constructor(name) {
this.name = name;
}

sayHello() {
console.log('Hello, my name is ' + this.name);
}

sayHelloAndBye() {
Person.prototype.sayHello.call(this);
console.log('Bye');
}
}

class Student extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
sayHello() {
console.log(`Hi, I'm a studend and my name is ` + this.name);
}
}

let b = new Student("Some guy", 5);

b.sayHelloAndBye();

关于javascript - ES6 javascript继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46792469/

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