如何从闭包中访问外部函数的 "arguments" 文字对象?

How to access the "arguments" literal object of an outer function from a closure?

我有一个闭包,我需要从该闭包访问定义闭包的函数的 arguments 对象字面量:

function outerFunction(){

    var myClosure = function(){
        // I need to access the "arguments" object of "outerFunction"
    }

}

如果不将 arguments 存储在变量中,这可能吗?

简短回答:只需使用一个变量。没有充分的理由

Is this possible without storing arguments in a variable?

您的选择是存储对 arguments 对象本身的引用,或者使用变量(或参数)从中引用单个项目,但您无法访问 arguments内部函数中外部函数的对象本身,因为它自己的 arguments 遮蔽了它。

在一种非常有限的情况下,您可以在不执行以下任一操作的情况下执行此操作: 调用 outerFunction 期间(不是稍后,如果 myClosure 存活 outerFuntion 返回)你可以使用 outerFunction.arguments。我不认为这是 记录的 行为(至少,我无法在规范中找到它),但它适用于 Chrome、Firefox 和 IE11。例如:

function outerFunction() {

  var myClosure = function(where) {
    snippet.log(where + " " + JSON.stringify(outerFunction.arguments));
  };

  myClosure("Inside");

  return myClosure;
}

var c = outerFunction(1, 2, 3);
c("Outside");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

我认为没有理由这样做,而且我认为它实际上不在规范中(我认为这是一些代码返回依赖的未指定行为,因此浏览器复制)。但它至少在某些引擎上工作,前提是你在 调用 outerFunction.

期间这样做

在你说的评论中

I would like to call it directly in order to automatise a task

这正是将它赋值给变量的作用,它可以在内部函数中使用外部函数的 arguments:

function outerFunction() {
  var args = arguments;

  var myClosure = function() {
    snippet.log(JSON.stringify(args));
  };

  return myClosure;
}

var c = outerFunction(1, 2, 3);
c();
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>