Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
应用时JavaScript对象错误中的jQuery事件_Javascript_Jquery_Events_Object - Fatal编程技术网

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

应用时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

我真的不明白如何在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' 
我想有一个合适的方法,但我找不到

谢谢你的帮助

编辑: 我真的不知道为什么它在我的示例中起作用,但在我的代码中却不起作用

试试看

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