未捕获的类型错误:方法不是函数

Uncaught TypeError: method is not a function

本文关键字:方法 函数 错误 类型      更新时间:2023-09-26

代码:

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

如果我单击添加预订元素,则会出现此错误:

未捕获的类型错误:this.checkAvailability 不是一个函数。

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

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

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