繁体   English   中英

有没有一种方法可以访问函数的父作用域中的变量

[英]Is there a method for accessing variables in the parent scopes of a function

给定对function的引用,是否可以在其父作用域中访问变量名称和/或值? 例如:

 let ref = (function myClosure() { const foo = 'foo'; const bar = 'bar'; return { sneaky() { // use the variables somehow // since some browsers optimize functions // by omitting parent scopes from the context // that are not used console.log(foo, bar); } }; }()); // given `ref.sneaky` in this scope, how to access the scope in `myClosure`? console.log(ref); 

在开发人员控制台中检查ref ,我们发现:

检查<code> ref </ code>

注意Closure对象,其中包含foobar 如果不可能以编程方式获得此关闭对象,那么是否存在任何当前提议的ECMAScript标准,例如Symbol.scope ,其中可能包含给定函数的父“关闭对象”的数组?

更新资料

为了解决@Bergi和@Oriol的评论,我要添加一些说明。

 let ref = (function myClosure() { const foo = 'foo'; const bar = 'bar'; return { sneaky(...variableNames) { // use the variables somehow // since some browsers optimize functions // by omitting parent scopes from the context // that are not used console.log(foo, bar); return Object.assign(...variableNames.map(variableName => ({ [variableName]: eval(variableName) }) )); } }; }()); // given `ref.sneaky` in this scope, how to access the scope in `myClosure`? console.log(ref.sneaky('foo', 'bar')); 

当然,如果提前知道变量名并且子作用域中存在一个eval ,这是eval ,但是如果这两个条件都不满足怎么办?

给定对函数的引用,是否可以以编程方式访问其父作用域中的变量名称和/或值?

没有。

目前是否有任何提议的ECMAScript标准(例如Symbol.scope可以包含给定函数的父级“关闭对象”的数组?

不会。如果存在,它将永远不会被接受,因为闭包是Javacript中真正封装的唯一方法,而引入这样的访问器将是一个巨大的安全漏洞(有关参考,请参见http://www.ieee-security .org / TC / SP2011 / PAPERS / 2011 / paper023.pdfhttp://web.emn.fr/x-info/sudholt/papers/miss13.pdf )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM