2013-07-28 43 views
1

我真的不明白如何在我的JavaScript对象中设置监听器。 例如:jQuery事件在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/

+0

在jsfiddle.net上重现它 – zerkms

+1

我无法重现该错误。该代码中唯一的错误是“Uncaught SyntaxError:Unexpected token}”,但是当我[修复并实例化类的实例以使该函数实际运行时](http://jsbin.com/aribuv/1/edit) ,代码正如我所期望的那样工作。 – Quentin

回答

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

感谢您的帮助,它的工作原理 – Ajouve