代码:
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/