【问题标题】:Uncaught TypeError: method is not a function未捕获的类型错误:方法不是函数
【发布时间】:2016-01-24 07:52:44
【问题描述】:

代码:

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 元素,我会收到此错误:

未捕获的类型错误:this.checkAvailability 不是函数。

【问题讨论】:

标签: javascript typeerror


【解决方案1】:

您需要更改事件的绑定方式。

addBooking.addEventListener('click', grandHotel.bookRoom.bind(grandHotel), false);

addBooking.addEventListener('click', function() { grandHotel.bookRoom(); }, false);

【讨论】:

  • 非常感谢您。现在我明白了,以为我可以直接在 addEventlistener 的函数参数中放置一个方法。非常感谢您的帮助先生。
  • @nikodeguzman 请注意,通过在闭包中捕获“this”(如var that=this; 并使用that 而不是this)来解决问题更为常见。
  • @AlexeiLevenkov 嗯,this 在哪里?我知道你在说什么,但在这种情况下没有这个,“这个”是grandHotel
  • @epascarello 失败了?如果 OP 将在 bookRoom 内使用 that.checkAvailability() ,那么它可以与添加事件侦听器的原始代码完美配合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 2019-06-06
  • 2019-05-24
  • 2021-12-15
  • 2019-10-26
  • 2016-06-27
相关资源
最近更新 更多