如何获取内联 javascript 回调函数的父作用域?
我有与此类似的东西
function testfunction(runthis)
{
runthis();
}
function main()
{
var z = 15;
testfunction(function(){ alert(z); });
}
,但是它认为 z 与我的内联函数不在同一范围内。在不向 testfunction 或我的内联函数添加额外参数的情况下,有没有办法让我的内联函数与 main 属于同一范围?我正在尝试使回调函数起作用。
编辑:我认为上面是一个蹩脚的例子,因为它似乎有效。但是,这里的实例 http://pastebin.com/A1pq8dJR 不起作用,除非我添加 .call(this,parameters )并手动设置范围(尽管我不太确定这是在做什么)。我本以为这里使用的 this 会指 imageLoaded 的范围,但它指的是 imageBoxCreate 的范围?谁能解释为什么没有它就无法工作以及为什么这样做可以修复它?
I have something similar to this
function testfunction(runthis)
{
runthis();
}
function main()
{
var z = 15;
testfunction(function(){ alert(z); });
}
However it doesn't think z is in the same scope as my inline function. Without adding additional parameters to testfunction or my inline function, is there any way for my inline function to belong to the same scope as main? I'm trying to make callback functions work.
Edit: the above I imagine is a crappy example because it seems to be working. However the instance here http://pastebin.com/A1pq8dJR does not work unless I add .call(this,parameters) and manually set the scope (although I'm not exactly sure what this is doing). I would have thought this used there would refer to the scope imageLoaded has, but it is referring to the scope of imageBoxCreate? Could anyone explain why it wont work without that and why doing this fixed it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只是在 javascript 中调用全局函数,则
this
对象将是顶级window
全局对象。如果您在对象上使用点运算符调用函数,则函数运行时this
将是该对象。当您使用function.call
时,您明确指定哪个对象应该是this
。我认为您可能只是在使用this
和var
的方式上犯了一些范围错误,但您的代码足够长并且涉及足够多,我不会花费是时候为您调试它了。如果您可以使用较小的代码示例来隔离问题,那么人们应该能够更轻松地提供帮助。If you just invoke a global function in javascript, the
this
object will be the top levelwindow
global object. If you invoke a function using the dot operator on an object, thenthis
will be that object when the function runs. When you usefunction.call
, you are explicitly specifying which object should bethis
. I think you are likely just making some scope mistakes with how you usethis
andvar
, but your code is long enough and involved enough that I'm not going to spend the time to debug it for you. If you can isolate you issue with a smaller code sample, folks should be able to help more easily.