JavaScript:将函数局部作用域作为对象引用 [英] JavaScript: Reference a functions local scope as an object
问题描述
当我调用一个函数时,会为该调用建立一个本地作用域.有没有办法直接将该范围作为对象引用?就像 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(code,1)
是实现全局作用域的一个简单有效的 hack,但它不会立即执行.
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 节).您只能访问通过 arguments
获得的有限视图(这确实非常有限).
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:将函数局部作用域作为对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!