为什么JavaScript Arguments对象通过赋值给参数而变异? [英] Why are JavaScript Arguments objects mutated by assignment to parameter?

查看:93
本文介绍了为什么JavaScript Arguments对象通过赋值给参数而变异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种行为背后的理由是什么?

What is the rationale behind this behaviour?

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

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

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

Perhaps this was a genuine mistake. Which section of the ECMAScript specification defines this behaviour?

推荐答案

实际上,在严格模式下,这确实不是发生在您可以在这里看到

Actually, in strict mode, this does not happen as you can see here.

如果您阅读了 ECMA标准的第10.6节,特别是注1,你会看到:

If you read section 10.6 of the ECMA Standard, in particular Note 1, you'll see:


对于非严格模式函数,数组索引(在15.4中定义) )参数对象
的命名数据属性,其数字名称值小于相应函数对象的形式参数的数量,最初
与函数执行上下文中的相应参数绑定共享它们的值。这意味着更改
属性会更改参数绑定的相应值,反之亦然。如果
此类属性被删除然后重新定义或者该属性被更改为存取属性,则此对应关系将被破坏。对于严格模式
函数,arguments对象的属性值只是传递给函数的参数的副本,
属性值和形式参数值之间没有动态链接。 / p>

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.

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

In short, what this is saying is that, in non-strict mode, named function parameters operate as aliases for items in the arguments object. Thus, changing the value of a named parameter will change the value of the equivalent arguments item and vice versa. This is not a mistake. This is expected behaviour.

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

As an editorial, it's probably not a good idea to rely on this behaviour as it can lead to some very confusing code. Also, such code, if executed in strict mode, would not longer work.

这篇关于为什么JavaScript Arguments对象通过赋值给参数而变异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆