在侦听器函数内调用方法时引用错误(Javascript)

Mar*_*sis 3 javascript oop scope

function LolClass(){

    this.init = function(){             
        button_a.bind("tap", function(){                
            this.refreshFields(); // doesn't work 
            //refreshFields(); // doesn't work either
        });     
    }

    this.refreshFields = function(){
        alert("LOL");
    }

    this.dummy = function(){
        this.refreshFields(); // W O R K S!
    }
}
Run Code Online (Sandbox Code Playgroud)

当我点击button_a时,我得到一个引用错误,因为没有"找到"refreshFields方法.

未捕获的ReferenceError:未在file:///android_asset/www/src/pages/main.js中定义refreshFields:70

但是如果我在其他地方调用该方法而不是那个tap侦听器,它就可以了.

我完全确定thistap tapner函数内部引用了事件目标button_a.

我的问题是:最好的(oo)解决方案是什么?

Tri*_*Nhu 8

试试这个

function LolClass(){

    var someVar = 0; 
    var self = this;

    this.init = function(){             
        button_a.bind("tap", function(){                
            self.refreshFields(); // now works!
            //refreshFields(); // doesn't work
        });     
    }

    this.refreshFields = function(){
        alert("LOL");
    }

    this.dummy = function(){
        this.refreshFields(); // W O R K S!
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 当你复制他的代码并修复它时,你可以删除"不工作"......`:)` (4认同)