为什么我的第二个参数的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
答案 0 :(得分:6)
return
getter:
height
get height(){
return this._height;
}