gpt4 book ai didi

javascript - 未捕获的类型错误 : method is not a function

转载 作者:行者123 更新时间:2023-11-29 19:20:23 25 4
gpt4 key购买 nike

代码:

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 元素,我会收到此错误:

Uncaught TypeError: this.checkAvailability is not a function.

最佳答案

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

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

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

关于javascript - 未捕获的类型错误 : method is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33325011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com