匿名事件处理程序无权访问prototype方法

时间:2013-10-16 18:09:18

标签: javascript

无法在匿名函数处理程序中从fx2访问fx1?

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

2 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:1)

另一种方法:

MyComponent.prototype.fx2 = function() {
    var btn1 = document.getElementById('Button1');
    btn1.onclick = (function() {
        this.fx1();
    }).bind(this);
}