在侦听器函数 (Javascript) 中调用方法时引用错误
Reference error when calling a method inside a listener function (Javascript)
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!
}
}
当我点击button_a时,我收到一个引用错误,因为"找不到"刷新字段方法。
未捕获的引用错误: 刷新字段未在 file:///android_asset/www/src/pages/main.js:70
但是,如果我在点击侦听器以外的其他地方调用该方法,它就可以工作。
我完全确定tap侦听器函数中的this
引用的是button_a,即事件目标。
我的问题是:最好的(oo)解决方案是什么?
试试这个
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!
}
}
你应该缓存this
:
var that = this; // "that" is a convention name for "this"
this.init = function(){
button_a.bind("tap", function(){
that.refreshFields();
});
}
您需要修改代码:
function LolClass(){
var someVar = 0;
var $this = this;
this.init = function(){
button_a.bind("tap", function(){
$this.refreshFields();
});
}
this.refreshFields = function(){
alert("LOL");
}
this.dummy = function(){
this.refreshFields(); // W O R K S!
}
}
回调中的"this"指的是不同的对象。我添加了 var $this = 这个;并在回调中使用$this。
相关文章:
- 如何在webView,Android中从@JavascriptInterface方法调用Javascript
- javascript从子方法调用父方法
- 我应该返回一个类似console.log()的方法调用吗
- NodeJS-从同一文件中的另一个方法调用一个方法
- 使用restangular save方法调用put与post时的控件
- 从实例方法调用实例方法
- Node.js-异步方法调用问题
- Jquery事件绑定获胜'当作为方法调用时不起作用,但当直接在控制台中调用时会起作用
- 向模板实例变量传递调用方法调用的结果时出现异常
- jQuery 方法调用了两次
- 不能从 Backbone.View 的方法调用 Backbone.collection 的方法,其中包含 require
- 组合 onLayout 的方法调用
- lodash/下划线 - 使用绑定与方法调用和方法保持未绑定
- 从公共方法调用模块的私有函数
- 如何对 jqGrid 的 loadComplete 和 onSelectRow 进行基因预和后方法调用
- 完全限定的 JavaScript 方法调用
- 为什么我在 Angular JS 中收到两个方法调用
- 如何在从排序方法调用参数时将其传递给回调
- 使用两种不同的方法调用方法
- 如何在 javascript 中更改方法调用的全局范围