JavaScript继承 - 未定义的值

时间:2016-01-19 21:32:21

标签: javascript inheritance ecmascript-6

如果我调用greet函数,有人可以解释为什么firstName和lastName是未定义的? 似乎两者都设置正确,所以我真的不知道什么是错的。我应该怎么做才能解决它。

'use strict';

class Person {
    constructor() {
        this.firstName = 'James';
        this.lastName = 'Bond';
    }

    greet() {
        console.log(`Hello ${this.firstname} ${this.lastname}`);
    }
}

class Employee extends Person {
    constructor() {
        super();
        this.salary = 1234;
    }
}

var employee = new Employee();

console.log(employee.firstName); //James
console.log(employee.lastName); //Bond
console.log(employee.salary); //1324

employee.greet(); //Hello undefined undefined

1 个答案:

答案 0 :(得分:3)

JavaScript是超级区分大小写的... firstname != firstName

你想:

console.log(`Hello ${this.firstName} ${this.lastName}`);
                               ^                ^