有人可以解释为什么hotel.availableRooms是NaN吗?我正在尝试用JavaScript学习对象。谢谢!
var hotel = {
name: 'The Shining',
totalRooms: 238,
bookedRooms: 0,
availableRooms: this.totalRooms - this.bookedRooms,
roomTypes: ['single', 'double', 'haunted'],
bookRoom: function() {
this.availableRooms -= 1;
this.bookedRooms += 1;
}
};
hotel.bookRoom();
console.log(hotel.totalRooms);
console.log(hotel.bookedRooms);
console.log(hotel.availableRooms);

答案 0 :(得分:1)
当评估表达式availableRooms: this.totalRooms - this.bookedRooms,
时,this
不是hotel
,而是运行代码的上下文。
var hotel = {
name: 'The Shining',
totalRooms: 238,
bookedRooms: 0,
roomTypes: ['single', 'double', 'haunted'],
bookRoom: function() {
this.availableRooms -= 1;
this.bookedRooms += 1;
}
}
hotel.availableRooms = hotel.totalRooms - hotel.bookedRooms
或者
Object.defineProperty(hotel, 'availableRooms', {
get: function() {
return this.totalRooms - this.bookedRooms
}
})