Reputation: 23
Code:
function Hotel(name,rooms,bookings){
this.name = name;
this.rooms = rooms;
this.bookings = bookings;
this.checkAvailability = function(){
return this.rooms - this.bookings;
}
this.bookRoom = function(){
if(this.checkAvailability() > 1){
return this.bookings++;
}
}
this.cancelBooking = function(){
if(this.bookings < 1){
return this.bookings--;
}
}
}
var grandHotel = new Hotel('Hotel Grand', 20, 5);
var addBooking = document.getElementById("book");
addBooking.addEventListener('click', grandHotel.bookRoom, false);
If I click the addBooking element I get this error:
Uncaught TypeError: this.checkAvailability is not a function.
Upvotes: 2
Views: 4296
Reputation: 207501
You need to change how the event is being bound.
addBooking.addEventListener('click', grandHotel.bookRoom.bind(grandHotel), false);
or
addBooking.addEventListener('click', function() { grandHotel.bookRoom(); }, false);
Upvotes: 3