如何在JavaScript中使用类方法作为onclick处理程序?

如何在JavaScript中使用类方法作为onclick处理程序?,javascript,class,javascript-objects,Javascript,Class,Javascript Objects,考虑以下Javascript类: function ClassA() { this.someVariable = someValue; this.myHandler = function(){ // I WANT TO CALL InnerFunction this.innerFunction(); }; this.innerFunction = function(){ // do something that accesses/manipulates someVar

考虑以下Javascript类:

function ClassA() {
 this.someVariable = someValue;
 this.myHandler = function(){
   // I WANT TO CALL InnerFunction
   this.innerFunction();
 };

 this.innerFunction = function(){
   // do something that accesses/manipulates someVariable
 };

 this.hookUp = function(id){
   document.getElementById(id).onclick = this.myHandler;
 };
};
...
...
var button = document.createElement('button');
button.setAttribute('id','mybuttonid');
// append button to the document
...
...
var x = new ClassA();
x.hookUp('mybuttonid');
当我单击按钮时,处理程序执行,“this”现在指的是button元素而不是ClassA对象,因此它无法解析innerFunction()

我需要的是一种向处理程序指示其上下文是ClassA实例的方法(类似于$.ajax({context:this…}),您可以在.done()或.error()处理程序中使用“this”),或者一种将实例引用传递给处理程序的方法,而无需在实例化时执行处理程序。例如,如果我尝试将“this”作为praremter传递给myHandler(myHandler=function(ref){},然后更改:document.getElementById(id).onclick=this.myHandler(this);) 但是,当您向myHandler添加参数时,函数将在类实例化时而不是在单击时执行


任何帮助都将不胜感激。

这是一个通常使用所谓的“代理模式”解决的问题

我想这会有帮助的


正如您已经发现的,this的值取决于方法的调用方式。因此,在附加到DOM元素的事件处理程序中使用this可能会造成混淆

相反,在添加处理程序时,在闭包中使用匿名方法和变量

例如,将连接功能更改为:

this.hookUp = function(id) {
    var _this = this;
    document.getElementById(id).onclick = function() {
      _this.innerFunction();
    }
}
请注意,您不再依赖onclick处理程序中的
thi
,从而避免了该问题。一旦进入
innerFunction
,您可以继续使用
this
,因为它现在正确地指向了正确的对象

要更深入地解释此如何在函数中工作,MDN有一个很好的

替换

this.myHandler = function(){
    this.innerFunction();
};
…与

var self = this;
this.myHandler = function() {   
    self.innerFunction();
};
见.引述:

按照惯例,我们创建一个私有的
,该
变量用于
私有方法可用的对象。这是
ECMAScript语言规范中的一个错误,导致
失败 内部功能的设置不正确


另请参见而不是
此。someVariable
尝试仅使用
var someVariable
someVariable
将仅在函数范围内可用,因此不需要
。JavaScript中也没有类,因此您使用
的想法可能会被误导anks..也许我不是很清楚,我的主要问题是访问innerFunction()。我正在尝试编写类似于OO的代码,以便更容易理解和维护,至少对我来说:)。先生,您为我节省了数小时寻找解决方案的时间。非常感谢。谢谢,很有用,解释得很好。