如何从回调中访问此类成员?
这个问题最好用一些代码来解释,所以这里是:
// a class
function a_class {
this.a_var = null;
this.a_function = a_class_a_function;
}
// a_class::a_function
function a_class_a_function() {
AFunctionThatTakesACallback(function() {
// How to access this.a_var?
});
}
// An instance
var instance = new a_class();
instance.a_function();
从 AFunctionThatTakesACallback()
的回调中,如何访问 this.a_var
?
This question is best explained with some code, so here it is:
// a class
function a_class {
this.a_var = null;
this.a_function = a_class_a_function;
}
// a_class::a_function
function a_class_a_function() {
AFunctionThatTakesACallback(function() {
// How to access this.a_var?
});
}
// An instance
var instance = new a_class();
instance.a_function();
From within the callback in AFunctionThatTakesACallback()
, how does one access this.a_var
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要通过创建引用它的局部变量来扩展
this
的范围,如下所示:您需要这样做的原因是因为
this
中的引用AFunctionThatTakesACallback
函数与当前对象的this
不同,它可能会引用全局window
对象。 (通常不是你想要的)。哦,我有没有提到这称为 closure< /强> ?
You'll need to expand the scope of
this
by creating a local variable that references it, like this:The reason why you need to do this is because the
this
reference within theAFunctionThatTakesACallback
function is not the samethis
as the current object, it will likely reference the globalwindow
object instead. (usually not what you want).Oh, did I mention that this is called a closure?
您可以尝试使用函数对象的 call 方法,该方法可以让您为此指定一个值:
但我认为在这种情况下,将“this”作为参数之一传递给回调可能会更直接。
You could try using the call method of function objects, which lets you specify a value for this:
But I think that in this case it would probably be more straightforward to pass 'this' in as one of the parameters to the callback.
当您调用
instance.a_function()
时,您实际上是在使用instance
作为this
调用a_class_a_function
,因此您可以像这样修改a_class_a_function
:这里的问题是,如果您尝试调用
a_class_a_function
而不从实例调用它,那么this
可能会引用到全局对象window
。When you call
instance.a_function()
, you're really callinga_class_a_function
withinstance
asthis
, so you can modifya_class_a_function
like so:The problem here is that if you attempt to call
a_class_a_function
without calling it from an instance, thenthis
will likely refer to the global object,window
.