ES6 javascript继承

时间:2017-10-17 14:22:22

标签: javascript oop ecmascript-6

提供以下代码:

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是否有类似的概念。

1 个答案:

答案 0 :(得分:4)

您可以参考sayHelloPerson的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();




相关问题