2013-07-05 32 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

相关问题