应用时JavaScript对象错误中的jQuery事件
我真的不明白如何在JavaScript对象中设置侦听器。 例如:应用时JavaScript对象错误中的jQuery事件,javascript,jquery,events,object,Javascript,Jquery,Events,Object,我真的不明白如何在JavaScript对象中设置侦听器。 例如: var obj = function(){ this.test = function(){ console.log('test'); } $(document).on('click','#test',(function(){ this.test(); }).bind(this)); } 但是jQuery给了我这个错误 Uncaught TypeError: Ob
var obj = function(){
this.test = function(){
console.log('test');
}
$(document).on('click','#test',(function(){
this.test();
}).bind(this));
}
但是jQuery给了我这个错误
Uncaught TypeError: Object #test has no method 'apply'
我想有一个合适的方法,但我找不到
谢谢你的帮助
编辑:
我真的不知道为什么它在我的示例中起作用,但在我的代码中却不起作用
试试看
var obj = function(){
this.test = function(){
console.log('test');
}
var t = this;
$(document).on('click','#test', function(){
t.test();
});
}
您也可以使用
$(document).on('click','#test', $.proxy(this.test, this));
或
在jsfiddle.netI上重现该错误。该代码中唯一的错误是“uncaughtsyntaxerror:unexpectedtoken}”,但当我输入时,代码的工作方式与我预期的一样。
$(document).on('click','#test', $.proxy(function () {
this.test();
}, this));