JavaScript:引用一个函数local scope作为对象 [英] JavaScript: Reference a functions local scope as an object

查看:197
本文介绍了JavaScript:引用一个函数local scope作为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我调用一个函数时,为该调用建立了一个本地范围。有没有办法直接将该范围作为对象引用?就像window是全局范围对象的引用一样。

When I call a function, a local scope is erected for that call. Is there any way to directly reference that scope as an object? Just like window is a reference for the global scope object.

示例:

function test(foo){
    var bar=1
    //Now, can I access the object containing foo, bar, arguments and anything
    //else within the local scope like this:
    magicIdentifier.bar
}

或者,是否有人有完整的在自定义变量之上的本地范围内的列表?

Alternately, does anyone have a complete list of what is in the local scope on top of custom variables?

背景:我正试图从一个完全转移到全局范围的方式函数调用,with语句是一个笑话,调用工作好一点,但它仍然在函数范围内声明但在全局范围内没有中断,因此我会在全局范围内声明这几个案例,但这需要我知道是什么他们是。 IE函数execScript完全转换,但这只解决了IE的问题。

Background: I'm trying to get down to a way of completely shifting to global scope from within a function call, the with statement is a joke, call works a little better, but it still breaks for anything declared in function scope but not in global scope, therefore I would declare these few cases in global scope, but that requires me to know what they are. The IE function execScript makes a complete shift, but that only solves the problem for IE.

注意:对任何动态加载JavaScript的人来说, setTimeout(代码,1)是一个简单有效的黑客来实现全局范围,但它不会立即执行。

Note: To anyone loading JavaScript dynamically, setTimeout(code,1) is a simple effective hack to achieve global scope, but it will not execute immediately.

推荐答案

不,没有办法引用 变量环境的函数 绑定对象的执行上下文的变量对象>执行上下文(这就是所谓的[现在;因此删除线]; 规范的§10.3)。您只能使用参数(实际上非​​常有限)访问有限的视图。

No, there's no way to reference the variable object of the execution context of a function binding object of the variable environment of the execution context (that's what that thing is called [now; hence the strikethrough]; details in §10.3 of the specification). You can only access the limited view to it you get with arguments (which is very limited indeed).

通常当我想要这样做的时候,我只是将我想要的东西放在一个对象上,然后使用它(例如,将它传递给一个函数)。当然,在上下文中创建的任何函数都可以访问创建它们的范围内的所有内容,因为它们关闭上下文;更多: 闭包并不复杂

Usually when I've wanted to do this, I've just put everything I wanted on an object and then used that (e.g., passed it into a function). Of course, any functions created within the context have access to everything in scope where they're created, as they "close over" the context; more: Closures are not complicated.

这篇关于JavaScript:引用一个函数local scope作为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆