javascript - 为什么 JavaScript Arguments 对象会因赋值给参数而发生变化?

标签 javascript ecmascript-5

这种行为背后的基本原理是什么?

function f(x) {
  console.log(arguments[0]);
  x = 42;
  console.log(arguments[0]);
}

f(1);
// => 1
// => 42

也许这是一个真正的错误。 ECMAScript 规范的哪一部分定义了这种行为?

最佳答案

实际上,在严格模式下,这不会发生为you can see here .

如果您阅读 ECMA Standard 的第 10.6 节,特别是注释 1,您会看到:

For non-strict mode functions the array index (defined in 15.4) named data properties of an arguments object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function‘s execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. For strict mode functions, the values of the arguments object‘s properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.

简而言之,这就是说,在非严格模式下,命名函数参数作为 arguments 对象中的项目的别名。因此,更改命名参数的值将更改等效 arguments 项的值,反之亦然。这不是错误。这是预期的行为。

作为社论,依赖这种行为可能不是一个好主意,因为它会导致一些非常困惑的代码。此外,如果在严格模式下执行此类代码,将不再有效。

关于javascript - 为什么 JavaScript Arguments 对象会因赋值给参数而发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16390539/

相关文章:

javascript - 在 Node.js 中使用 JavaScript 从 JSON 对象获取和设置文本内容

javascript - 如何强制谷歌闭包编译器保留 "use strict";在编译的js代码中?

javascript - 如何重构这个 Redux 连接代码?

javascript - [[Set]] 对象的属性

javascript - 这个循环在 Es5/Es6 上如何工作?

javascript - jqGrid 的替代方案,只是使用 ajax 的编辑功能

javascript - 为什么这个 javascript 函数会在错误的时间激活?

javascript - “原型(prototype)”抛出 TypeError : info is undefined

javascript - 当任何其他类函数被调用时运行一个函数

javascript - 循环遍历 div 的所有子级