javascript arguments 共享问题
function foo(a, b, c) { arguments[0] = 2; alert(a); // chrome bomb! c = 3; alert(arguments[2]); // 此处不应共享应为undefined } foo(1, 2); |
没有赋值的arguments对象项(c)是不应该具有共享性的.但Chrome却埋了这个地雷.
附上文档规范:
My confusion stemmed from Section 10.6 Note 1 of ECMA-262, 5th Edition, which reads:
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.
如果是实参小于等于虚参,那么arguments和实参是对应绑定的。也就是实参改变了,arguments会共享。如果arguments键值改变也会影响到对应实参。
但如果实参数目大于虚参数目,那么没有对应相对应的实参(如上文代码的c参数),arguments是不会为他分配插槽的。因为规范规定。arguments的数字索引是根据实参个数来分配的。所以对于上文代码c根本没有对应索引。那么arguments[2]就是undefined直接量。也无法为其赋值去影响实参。
转载于:https://www.cnblogs.com/bluedream2009/archive/2010/04/14/1712068.html
更详细的说明参考:
http://www.nczonline.net/blog/2010/11/02/mysterious-arguments-object-assignments/
希望不止
将来的你
一定会感谢现在拼命的自己
fighting!!!