2016-02-12 45 views
0

如何在调用makeBooking方法时获取预订属性。没有得到理想的结果,我在做什么错误学习JavaScript。如何使用该对象中的方法增加对象中的属性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

你可以做'this.booked ++;',而不是说'addBooked'变量 –

+0

addBooking + = 1 – ambes

+0

请使用this.booked ++。增加预订指向一个只有this.booked值的新变量。 – Vatsal

回答

0

this.booked ++,当你ASIGN简单类型的变量不链接回原产权

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)

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它不指向原来的变量。

希望这有些帮助。

快乐学习

+0

谢谢你的工作。是越来越好。 – mikeal

相关问题