[英]Uncaught typeError: not a function for a private method in TypeScript
[英]Uncaught TypeError: method is not a function
码:
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元素,则会出现此错误:
未捕获的TypeError:this.checkAvailability不是函数。
您需要更改事件的绑定方式。
addBooking.addEventListener('click', grandHotel.bookRoom.bind(grandHotel), false);
要么
addBooking.addEventListener('click', function() { grandHotel.bookRoom(); }, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.