如何访问“参数”来自闭包的外部函数的文字对象

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

本文关键字:闭包 自闭 外部 函数 对象 文字 何访问 访问 参数      更新时间:2023-09-26

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

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

不将arguments存储在变量中是可能的吗?

简短回答:只需使用变量。没有好的理由不

是否可以不将参数存储在变量中?

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

在一种非常有限的情况下,您可以不执行上述任何一种操作:调用outerFunction期间(如果myClosureouterFuntion返回后存活),您可以使用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期间执行


在评论中你说

我想直接调用它,以便自动执行任务

这就是将它赋值给变量所做的事情,它使得可以在内部函数中使用外部函数的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>