提供以下代码:
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是否有类似的概念。
答案 0 :(得分:4)
您可以参考sayHello
到Person
的prototype属性中定义的Person
版本,并使用Function#call
使用必要的this
进行调用:
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();