繁体   English   中英

ES6 JavaScript继承

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM