这是javascript类构造函数中没有定义的错误?

时间:2016-06-29 03:03:02

标签: javascript class

我在Employee课程中无法获取我的名字参数!我不知道为什么会收到 this is not undefined 这样的错误! this适用于当前对象!我不知道如何输出我的名字参数?

class Person {
    constructor(n, a) {
        var p = this;
        p.n = n;
        p.a = a;
        p.total = 0;
        p.a.map(x => p.total += parseInt(x)); //get total salary     
    }
    firstName() {
        return this.n = "Min Min ";
    }
    displayMsg() {
        return " and My yearly income is " + this.total;
    }
}

class Employee extends Person {
    constructor(name, age) {
        this.name = name;
    }
    lastName() {
        return this.name;
    }
    Show() {
        return "My name is " + super.firstName() + this.lastName() + super.displayMsg();
    }
}
emp = new Employee("David", [123, 456, 754]);
console.log(emp.Show());

实际输出

Uncaught ReferenceError: this is not defined

预期输出

My name is Min Min David  and My yearly income is 1333

1 个答案:

答案 0 :(得分:11)

您需要先再次调用super()构造函数,然后才能继续实例化您的类:

class Employee extends Person {
    constructor(name, age) {
        super(name, age);
        this.name = name;
    }

    ...
}

JSBin