我真的不知道如何在JavaScript对象中设置侦听器。例如:
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'
我想有一个合适的方法,但我找不到。
谢谢你的帮助。
编辑:我真的不知道为什么它在我的例子中有效,但在我的代码中无效
http://jsfiddle.net/nhJNH/
尝试
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));
或
$(document).on('click','#test', $.proxy(function () {
this.test();
}, this));