我正在尝试从 jquery 事件处理程序调用原型(prototype)方法。我有这样的代码:
$('#' + this.ID + ' .selMake').on('change', this.getCarModel());
我收到一条错误消息: 未捕获的类型错误:对象 [object global] 没有方法“getCarModel”
我在这里做错了什么?
最佳答案
您需要做的第一件事是从函数中删除括号。您的代码当前期望的是 getCarModel
返回一个函数,然后在触发事件时调用该函数。
看起来这就是您想要做的:
$('#' + this.ID + ' .selMake').on('change', that.getCarModel);
不是这个:
$('#' + this.ID + ' .selMake').on('change', that.getCarModel());
如果你想以这种方式调用该函数,你可以这样做:
var that = this;
$('#' + this.ID + ' .selMake').on('change', function () {
that.getCarModel();
});
在上面,您传递了一个匿名函数作为参数,该函数将执行其中的代码。
在上面的函数中,this
的定义将取决于触发事件的元素。如果您希望将 this
的定义绑定(bind)到您的 this
对象,您可以执行以下操作:
最简单、易于理解的方法是使用 that
变量:
var that;
$('#' + this.ID + ' .selMake').on('change', that.getCarModel); // This will execute the function this.getcarModel
您还可以在支持 ES5 的浏览器中使用 bind
方法。
$('#' + this.ID + ' .selMake').on('change', this.getCarModel.bind(this));
关于javascript - 从另一个方法调用原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25753060/