Javascript 匿名事件处理程序不';我无法使用原型方法

Javascript 匿名事件处理程序不';我无法使用原型方法,javascript,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(

无法从匿名函数处理程序中的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. 
    }
}

由于
绑定到
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();
    }
}

由于
绑定到
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();
    }
}

另一种方法是:

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

另一种方法是:

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

那么你到底尝试了什么?你是如何访问它的?你把代码漏掉了question@devnull69-OPs注释
试图从此处调用fx1,但无法访问它。
表示他使用了
this.fx1()试图从此处调用fx1,但无法访问它。
表示他使用了
this.fx1()