本文介绍了未捕获的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元素,我会收到此错误:
If I click the addBooking element I get this error:
Uncaught TypeError:this.checkAvailability不是函数。
Uncaught TypeError: this.checkAvailability is not a function.
推荐答案
您需要更改事件的绑定方式。
You need to change how the event is being bound.
addBooking.addEventListener('click', grandHotel.bookRoom.bind(grandHotel), false);或
addBooking.addEventListener('click', function() { grandHotel.bookRoom(); }, false);更多推荐
未捕获的TypeError:方法不是函数
发布评论