如何获取内联 javascript 回调函数的父作用域?

发布于 2024-11-14 17:34:30 字数 575 浏览 4 评论 0原文

我有与此类似的东西

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

春花秋月 2024-11-21 17:34:30

如果您只是在 javascript 中调用全局函数,则 this 对象将是顶级 window 全局对象。如果您在对象上使用点运算符调用函数,则函数运行时 this 将是该对象。当您使用function.call时,您明确指定哪个对象应该是this。我认为您可能只是在使用 thisvar 的方式上犯了一些范围错误,但您的代码足够长并且涉及足够多,我不会花费是时候为您调试它了。如果您可以使用较小的代码示例来隔离问题,那么人们应该能够更轻松地提供帮助。

If you just invoke a global function in javascript, the this object will be the top level window global object. If you invoke a function using the dot operator on an object, then this will be that object when the function runs. When you use function.call, you are explicitly specifying which object should be this. I think you are likely just making some scope mistakes with how you use this and var, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文