gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:39:51 29 4
gpt4 key购买 nike

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

最佳答案

当表达式 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
}
})

关于javascript - 为什么这个对象变量表达式不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43134419/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com