【发布时间】:2012-05-09 12:21:06
【问题描述】:
我知道当我需要访问类成员函数时,我必须在 JS 类中保留对 this 的引用。但是,我目前正在努力处理以下(简化的)代码:
function MySimpleClass(p, arr) {
this.proxy = p;
this.contentArray = arr;
this.doStuff = function(callback) {
var self = this;
// at this point this.contentArray holds data
this.proxy.calculate(function(data) {
// inside the anonymous function this.contentArray is undefined
var el = self.contentArray[0]; // <-- will fail
// do something with el
callback.call(this, data);
});
}}
感谢任何帮助!
【问题讨论】:
-
这段代码对我来说不会失败。
-
哦,不过还是谢谢你看一看。
标签: javascript function scope anonymous