2013-10-16 93 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); 
} 
相關問題