应用中JavaScript对象中的jQuery事件错误

时间:2013-07-28 10:07:32

标签: 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: Object #test has no method 'apply' 

我认为有一种正确的方法,但我无法找到。

感谢您的帮助。

编辑: 我不知道为什么它在我的例子中起作用而在我的代码中不起作用

http://jsfiddle.net/nhJNH/

1 个答案:

答案 0 :(得分:2)

尝试

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));