2

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.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
nikodeguzman
  • 23
  • 1
  • 4
  • Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Alexei Levenkov Oct 25 '15 at 01:31

1 Answers1

3

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);
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Thank you so much for this. Now i get it, thought I can directly place a method in the function parameter of the addEventlistener . Truly appreciate your help sir. – nikodeguzman Oct 25 '15 at 01:16
  • @nikodeguzman note that the problem is way more commonly solved by capturing "this" in closure (like `var that=this;` and using `that` instead of this). – Alexei Levenkov Oct 25 '15 at 01:34
  • @AlexeiLevenkov Um, Where is the `this` here? I know what you are saying, but in this case there is no this, The "this" is `grandHotel` – epascarello Oct 25 '15 at 01:36
  • @epascarello on the line that failed? If OP would use `that.checkAvailability()` inside `bookRoom` it would work perfectly fine with original code to add event listener. – Alexei Levenkov Oct 25 '15 at 01:40