简体   繁体   English

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

[英]Uncaught TypeError: method is not a function

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: 如果单击addBooking元素,则会出现此错误:

Uncaught TypeError: this.checkAvailability is not a function. 未捕获的TypeError:this.checkAvailability不是函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM