我正在使用以下代码,但它返回以下错误:
Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'userInput'
这是代码 jsfiddle :
var ClickEvent = function (event) {
this.ev = $('.' + event);
this.ev.on('click', function () { this.userInput(); });
};
ClickEvent.prototype = function () {
return {
userInput: function () {
console.log('user');
},
show: function () {
console.log('show');
}
};
}();
var c = new ClickEvent('event');
我在 on()
回调函数中调用 userInput
函数,但它返回上述错误。
我该如何解决这个问题?
最佳答案
问题是点击回调处理程序中的执行上下文 (this
) 没有指向 ClickEvent
实例,它引用的是被点击的 dom 元素。
你需要使用
this.ev.on('click', $.proxy(function () { this.userInput(); }, this));
演示:Fiddle
或
var that = this;
this.ev.on('click', function () { that.userInput(); });
演示:Fiddle
关于javascript - 对象在 JavaScript 中没有方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17654495/