【问题标题】:re-declaring arguments variable doesn't throw any error - JavaScript重新声明参数变量不会引发任何错误 - JavaScript
【发布时间】:2020-11-30 11:46:50
【问题描述】:

阅读有关the arguments object at mdn 的文档。

arguments 对象是所有非箭头函数中可用的局部变量。您可以通过使用 arguments 对象来引用该函数内部的函数参数。

它说arguments 是一个局部变量,但是如果我使用let/const 重新声明它,则不会引发错误,不像普通的那样。

function fn(arg1) {
  // let arg1 = []; // Uncaught SyntaxError: Identifier 'arg1' has already been declared
  let arguments = []; // array or whatever, no error
}

所以我的问题是为什么不重新声明 arguments 变量会引发任何错误?

【问题讨论】:

    标签: javascript function arguments local-variables


    【解决方案1】:

    在严格模式下,使用arguments(或eval)作为变量名是语法错误:

    function fn(arg1) {
      "use strict";
      let arguments;
    }
    

    在草率模式下,您只是遮蔽letfunction 或参数声明替换隐式变量。如果您使用名称 arguments 创建自己的变量,则根本不会创建 Arguments 对象,因此它不会与您的代码冲突。它不是重新声明 var arguments - 隐含的 arguments 变量是有条件地创建的。

    不过,如果您显式编写 var arguments,这并不能阻止隐式创建,但也不会覆盖它。

    【讨论】:

    • 如果已经是函数的局部变量,怎么会被遮蔽呢?我的意思是,如果 arguments 在外部范围内声明可能有意义,不是这样吗?
    • 我查了一下,这里的“阴影”是错误的术语。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多