[英]ES6 javascript inheritance
提供了以下代码:
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();
我想找出一种调用Person
而不是Student
定义的sayHello
的方式。 可能吗 ?
在php中有self::
,它允许执行此操作,但是我不确定JS是否具有类似的概念。
您可以通过Person
的prototype属性引用Person
定义的sayHello
的版本,并使用Function#call
this
进行必要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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.