为什么这个对象变量表达式不起作用?

时间:2017-03-31 07:00:40

标签: javascript

有人可以解释为什么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);




1 个答案:

答案 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
      }
  })