Why are JavaScript Arguments objects mutated by assignment to parameter?

后端 未结 2 2210
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 11:15

What is the rationale behind this behaviour?

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

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


        
2条回答
  •  隐瞒了意图╮
    2021-02-13 11:54

    Altering x is reflected in arguments[0] because indexes of arguments may be getter/setters for the matching named argument. This is defined under step 11.c.ii of 10.6:

    1. Add name as an element of the list mappedNames.

    2. Let g be the result of calling the MakeArgGetter abstract operation with arguments name and env.

    3. Let p be the result of calling the MakeArgSetter abstract operation with arguments name and env.

    4. Call the [[DefineOwnProperty]] internal method of map passing ToString(indx), the Property Descriptor {[[Set]]: p, [[Get]]: g, [[Configurable]]: true}, and false as arguments.

    As noted in the steps above that, this requires that strict is false and, in this case, that f is called with a value for x:

    f()  // undefined, undefined (no argument, no getter/setter)
    f(1) // 1, 42
    

提交回复
热议问题