2013-10-16 94 views
1

无法从匿名函数处理程序中的fx2访问fx1?匿名事件处理程序无法访问原型方法

var MyComponent = function() { 
    //my constructor 
} 

MyComponent.prototype.fx1 = function() { //code } 

MyComponent.prototype.fx2 = function() { 

    var btn1 = document.getElementById('Button1') 

    btn1.onclick = function() { 
     //issue is here 
     //trying to call fx1 from here but can't access it. 

     this.fx1(); //doesn't work. 
    } 
} 
+0

那么究竟你试试? – devnull69

+0

你在哪里访问它? –

+0

您遗漏了代码 – Musa

回答

5

由于this绑定到onclick处理程序中的按钮,你不能用它来访问MyComponent实例。但是,你可以简单地保存在另一个变量引用您然后可以使用:

MyComponent.prototype.fx2 = function() { 
    // save reference to the instance 
    var self = this; 

    var btn1 = document.getElementById('Button1') 
    btn1.onclick = function() { 
     // access the saved reference to the MyComponent instance 
     self.fx1(); 
    } 
} 
+1

如果我们继续回答首先没有显示OP的努力的问题,问题就不会变得更好。但现在很好,所以要做我的客人:-) – devnull69

+0

@ devnull69说实话,我立刻明白了问题所在,对我来说这已经足够明显了。顺便说一句,作为社区的一员,现在你非常欢迎你改进这个问题,因为你知道它是关于什么的。 – poke

1

另一种方式来做到这一点:

MyComponent.prototype.fx2 = function() { 
    var btn1 = document.getElementById('Button1'); 
    btn1.onclick = (function() { 
     this.fx1(); 
    }).bind(this); 
} 
相关问题