Provided the following code:
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();
I would like to figure out a way of calling sayHello
as defined in Person
and not in Student
. Is it possible ?
In php there is the self::
which allows one to do this, but I'm not sure if JS has a similar concept.
You can refer to the version of sayHello
defined in Person
through Person
's prototype property and call it with the requisite this
using Function#call
:
sayHelloAndBye() {
Person.prototype.sayHello.call(this);
console.log('Bye');
}
Runnable:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.