2016-02-12 71 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

相關問題