当调用makeBooking
方法时,如何让预订的属性增加。没有得到理想的结果,我在学习JavaScript时做错了什么。
var hotel = {
name: "pacific",
rooms: 40,
bookings: 35,
booked: 30,
roomType: ['deluxe', 'double', 'suite'],
pool: true,
gym: true,
checkAvailability: function() {
return this.rooms - this.booked;
},
makeBooking: function() {
var roomSpace = this.checkAvailability();
var addBooking = this.booked;
if (roomSpace > 0) {
addBooking = addBooking++;
console.log('room has been booked');
} else {
console.log('no room available');
}
}
};
console.log(hotel.checkAvailability());
var roomTypePush = hotel.roomType;
roomTypePush.push('rental');
console.log(roomTypePush);
console.log(hotel.booked);
console.log(hotel.makeBooking());
console.log(hotel.booked)

答案 0 :(得分:0)
this.booked ++,当你将一个简单类型设置为变量时,它不会链接回原始属性
var hotel = {
name: "pacific",
rooms: 40,
bookings: 35,
booked: 30,
roomType: ['deluxe', 'double', 'suite'],
pool: true,
gym: true,
checkAvailability: function() {
return this.rooms - this.booked;
},
makeBooking: function() {
var roomSpace = this.checkAvailability();
if (roomSpace > 0) {
this.booked++;
console.log('room has been booked');
} else {
console.log('no room available');
}
}
};
console.log(hotel.checkAvailability());
var roomTypePush = hotel.roomType;
roomTypePush.push('rental');
console.log(roomTypePush);
console.log(hotel.booked);
console.log(hotel.makeBooking());
console.log(hotel.booked)

答案 1 :(得分:0)
请使用此代码段。
var hotel = {
name: "pacific",
rooms: 40,
bookings: 35,
booked: 30,
roomType: ['deluxe', 'double', 'suite'],
pool: true,
gym: true,
checkAvailability: function() {
return this.rooms - this.booked;
},
makeBooking: function() {
var roomSpace = this.checkAvailability();
var addBooking = this.booked;
if (roomSpace > 0) {
addBooking = this.booked++
console.log('room has been booked');
} else {
console.log('no room available');
}
}
};
console.log(hotel.checkAvailability());
var roomTypePush = hotel.roomType;
roomTypePush.push('rental');
console.log(roomTypePush);
console.log(hotel.booked);
console.log(hotel.makeBooking());
console.log(hotel.booked)
当你执行addbooking = this.booked然后增加addbooking时,它不会指向原始变量。
希望这会有所帮助。
快乐学习