[英]how to increment property in an object with a method in that object javascript
调用makeBooking
方法时,如何增加booked属性。 没有获得理想的结果,我在学习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)
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)
请使用此代码段。
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时,它并不指向原始变量。
希望这会有所帮助。
快乐学习
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.