javascript类为什么第二个参数getter不在下面工作

时间:2017-01-29 18:15:16

标签: javascript class setter getter

为什么我的第二个参数的getter在下面的代码段中返回undefined?它适用于年龄参数,但不适用于身高。如果您使用_param访问它,一切都很好,您可以从下面的输出中看到:

class Person {
    constructor(myage, myheight){
        this.age = myage;
        this.height = myheight;
    }

    get age(){
        return this._age;
    }

    set age(myage){
        this._age = myage;
    }

    get height(){
        this._height;
    }

    set height(myheight){
        this._height = myheight;
    }
 }

 var p = new Person(10, '5 feet');
 console.log(p);

 console.log(`age = ${p.age} and height = ${p.height}`);
 console.log(p.height);

正确生成年龄但不是高度

的值
 bash-3.2$ node classes.js
 Person { _age: 10, _height: '5 feet' }
 age = 10 and height = undefined
 undefined

1 个答案:

答案 0 :(得分:6)

return getter:

中缺少height
get height(){
    return this._height;
}