首页 > 解决方案 > ES6 类继承不继承

问题描述

我正在学习 ES6 视频教程并重新创建用例以更好地理解语法。

我是关于类继承的主题。我创建了一个由 Employee 扩展的超类 Person,我还有一个扩展 Employee 的实习生类。我doWork()在 Person 类中有一个名为“”的函数,它返回“paid”,在 Intern 类中,我试图通过让它返回“free”来覆盖“doWork”。

我指定康纳为新员工,贝丝为新实习生。问题是在我调用 doWork() 之后,我只在来自 beth.doWork() 的 console.log 中看到“Intern Free”。connor.doWork() 不应该返回“Employee Paid”,因为 Employee 正在扩展 Person 类?

class Person {
    constructor(name) {
        this.name = name;
    }
    get name() {
        return this._name;
    }
    set name(newValue) {
        if(newValue) {
            this._name = newValue;
        }
    }
    doWork() {
        return 'Paid Employee';
    }
}

class Employee extends Person {
    constructor(title, name) {
        super(name);
        this._title = title;
    }
    get title() {
        return this._title;
    }
}

class Intern extends Employee {
    doWork() {
        return 'Intern Free'
    }
}

let makeEveryoneWork = function(...people) {
    var results = [];
    for(var i = 0; i < people.length; i++) {
        results.push(people[i].doWork());
    }
    return results
}

let connor = new Employee("Doctor", "Connor");
let beth = new Intern("Student", "Beth");

connor.doWork();  //expecting to be 'Employee Paid'
beth.doWork();  // exprecting to be 'Intern Free'

标签: javascriptclassinheritance

解决方案


class Person {
    constructor(name) {
        this.name = name;
    }
    get name() {
        return this._name;
    }
    set name(newValue) {
        if(newValue) {
            this._name = newValue;
        }
    }
    doWork() {
        return 'Paid Employee';
    }
}

class Employee extends Person {
    constructor(title, name) {
        super(name);
        this._title = title;
    }
    get title() {
        return this._title;
    }
}

class Intern extends Employee {
    doWork() {
        return 'Intern Free'
    }
}

let makeEveryoneWork = function(...people) {
    var results = [];
    for(var i = 0; i < people.length; i++) {
        results.push(people[i].doWork());
    }
    return results
}

let connor = new Employee("Doctor", "Connor");
let beth = new Intern("Student", "Beth");

console.log(connor.doWork())  //expecting to be 'Employee Paid'
console.log(beth.doWork())  // exprecting to be 'Intern Free'

对我来说没问题。运行代码段。我只是复制粘贴了您的代码,并稍作更改。我将最后两行包裹在 console.log 调用中。


推荐阅读