Javascript 未捕获的TypeError:方法不是函数
代码:Javascript 未捕获的TypeError:方法不是函数,javascript,typeerror,Javascript,Typeerror,代码: 多功能酒店(名称、房间、预订){ this.name=名称; 这个房间=房间; 这个。预订=预订; this.checkAvailability=函数(){ 返回this.rooms-this.bookings; } this.bookRoom=函数(){ if(this.checkAvailability()>1){ 退回这个。预订++; } } this.cancelBooking=函数(){ 如果(这是预订
多功能酒店(名称、房间、预订){
this.name=名称;
这个房间=房间;
这个。预订=预订;
this.checkAvailability=函数(){
返回this.rooms-this.bookings;
}
this.bookRoom=函数(){
if(this.checkAvailability()>1){
退回这个。预订++;
}
}
this.cancelBooking=函数(){
如果(这是预订<1){
退回此项。预订--;
}
}
}
var grandHotel=新酒店(“大酒店”,20,5);
var addBooking=document.getElementById(“book”);
addBooking.addEventListener('click',grandHotel.bookRoom,false);
如果单击addBooking元素,则会出现以下错误:
未捕获类型错误:this.checkAvailability不是函数
您需要更改事件的绑定方式
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);
或
非常感谢你这么做。现在我明白了,我想我可以直接在addEventlistener的函数参数中放置一个方法。非常感谢您的帮助,先生。@nikodeguzman注意到,通过在闭包中捕获“this”(如
var that=this;
并使用that
代替此),问题通常会得到解决。@AlexeiLevenkov Um,这里的this
在哪里?我知道你在说什么,但在这种情况下没有这个,“这个”是grandHotel
@epascarello在失败的线路上?如果OP在bookRoom
内部使用that.checkAvailability()
,则可以使用原始代码添加事件侦听器
addBooking.addEventListener('click', grandHotel.bookRoom.bind(grandHotel), false);
addBooking.addEventListener('click', function() { grandHotel.bookRoom(); }, false);