2013-07-05 30 views
0

我是JavaScript編程新手。以下是我的代碼,非常簡單。我只是不知道爲什麼c.calculate()會提示正確的編號(5),但如果點擊按鈕,將會提示undefined。以及如何更改代碼以讓「點擊」提醒數字5?爲什麼我不能在我的javascript代碼中使用事件綁定來訪問「內部變量」?

//testing 
var Cal = function(){ 
    this.x = 5;    
} 

Cal.prototype.calculate = function(){ 
    alert(this.x); 
} 

Cal.prototype.add_button = function(){ 
    var mybutton = $("<button id='test'>test</button>").appendTo('body'); // I am using Jquery 
    mybutton.bind('click',this.calculate); 
} 

var c = new Cal();   
c.add_button(); // when click on the 'test' button, will alert "undefined" 
c.calculate(); // will alert '5' 
+0

'this'是不同的。 – SLaks

回答

0

正如SLaks所說,this指向的其他對象不是c。試試這個:

Cal.prototype.add_button = function(){ 
    var mybutton = $("<button id='test'>test</button>").appendTo('body'); // I am using Jquery 
    var that = this; //important 
    mybutton.bind('click',function(){ 
     return that.calculate(); 
    }); 
} 
+1

甚至可能'返回that.calculate();' – zerkms

+0

謝謝!這也適用! – pength

相關問題