我是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'
'this'是不同的。 – SLaks