为什么我可以't访问“;内部变量“;在我的javascript代码中使用事件绑定

why I can't access the "inner variable" with event binding in my javascript code?

本文关键字:代码 javascript 事件 我的 绑定 变量 我可以 访问 为什么 内部      更新时间:2023-09-26

我是javascript编程的新手。下面是我的代码,它非常简单。我只是不知道为什么c.calculate()会提醒右边的数字(5),但如果点击按钮,就会提醒undefined。以及如何更改代码以让"点击"警报编号为5?

//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'

要设置正确的上下文,您可以使用(只要您已经在使用jquery):

mybutton.bind('click', $.proxy(this.calculate, this));

mybutton.bind('click', this.calculate.bind(this));

后者的支持是有限的(参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Browser_compatibility)

正如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();
    });
}