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

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

给定对 function 的引用,是否可以访问其父范围中的变量名称 and/or 值?例如:

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,我们发现:

注意包含 foobarClosure 对象。如果无法以编程方式获取此闭包对象,是否有任何当前提出的 ECMAScript 标准,例如 Symbol.scope 可以包含给定函数的父 "closure objects" 数组?

更新

为了解决@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,这会起作用,但是如果这两个条件都不满足怎么办?

Given a reference to a function, is it possible to programmatically access the variable names and/or values in its parent scopes?

没有

Is there any currently proposed ECMAScript standard like say, Symbol.scope that could contain the array of parent "closure objects" of a given function?

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