未捕获的TypeError:方法不是函数

未捕获的TypeError:方法不是函数

问题描述:

代码:

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);

如果我点击addBooking元素,我会收到此错误:

If I click the addBooking element I get this error:


Uncaught TypeError:this.checkAvailability不是函数。

Uncaught TypeError: this.checkAvailability is not a function.


您需要更改事件的绑定方式。

You need to change how the event is being bound.

addBooking.addEventListener('click', grandHotel.bookRoom.bind(grandHotel), false);

addBooking.addEventListener('click', function() { grandHotel.bookRoom(); }, false);