Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获的TypeError:方法不是函数_Javascript_Typeerror - Fatal编程技术网

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