1

Can't access fx1 from fx2 inside an anonymous function handler?

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. 
    }
}
4

2 回答 2

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();
    }
}
于 2013-10-16T18:11:48.550 回答
1

另一种方法:

MyComponent.prototype.fx2 = function() {
    var btn1 = document.getElementById('Button1');
    btn1.onclick = (function() {
        this.fx1();
    }).bind(this);
}
于 2013-10-16T18:21:00.373 回答