let person = {
_name: 'Lu Xun',
_age: 137,
set age(ageIn) {
if (typeof ageIn === 'number') {
this._age = ageIn;
}
else {
console.log('Invalid input');
return 'Invalid input';
}
}
};
console.log(person.set age('bdhh'));
//执行代码时会将错误视为未捕获的引用 错误
答案 0 :(得分:1)
你以错误的方式调用setter。
person.age = 15; // this is how you call your setter
在jsFiddle中查看您的更新代码:https://jsfiddle.net/t3uzpobn/4/
答案 1 :(得分:0)
调用setter的方式不正确:
let person = {
_name: 'Lu Xun',
_age: 137,
set age(ageIn) {
if (typeof ageIn === 'number') {
this._age = ageIn;
}
else {
console.log('Invalid input');
return 'Invalid input';
}
}
};
console.log(person.age = 'bdhh');
console.log(person.age = 13);
答案 2 :(得分:0)
您的通话方法不正确
let person = {
_name: 'Lu Xun',
_age: 137,
set age(ageIn) {
if (typeof ageIn === 'number') {
this._age = ageIn;
}
else {
console.log('Invalid input');
return 'Invalid input';
}
}
};
console.log(person.age = 'bdhh');