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

标签 javascript typeerror

代码:

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/

相关文章:

javascript - li.parent 不是函数

javascript - react 。如何仅对现有 key 使用 fetch 和 setState 来处理 API 响应中丢失的 key ?

ruby-on-rails - ruby on rails TypeError in Users#show - 无法访问 Like

python - "Can' t 将 'float' 对象隐式转换为 str"

javascript - 此联系表单代码有什么问题?

javascript - 右移 o.length 为零

javascript - 我尝试使用 ajax 部分刷新 html,但它不起作用

Python 多处理,类型错误

python - TypeError: 'float' 对象不可下标 --Python

javascript - 方法 .includes() 不是函数错误