Scope of variables inside inline function default

2020-03-27 07:41发布

ES6 introduced default parameters. I'm trying to understand how inline function default parameters work with this new feature. Specifically how its scoping work.

Take for example the following two functions:

function one(x, f = function (){return x})
{
    var x = 5;
    console.log([x,f()]);
}

function two(x, f = function (){return x})
{
    x = 5;
    console.log([x,f()]);
}

one(1);//[5,1]
two(1);//[5,5]

Is it correct to say that, in function one, f keeps it's own closure scope for x in the parameter list, so that when the function redefines x as a new var: var x = 5;, the reference that f has, is not the same as the one inside the function?

If that's the case, is function one equal to function three below:

function three(x,f)
{
    var x2 = x;
    f = f !== undefined ? f : () => x2;
    var x = 5;
    console.log([x,f()]); //[5,1]
}

I tried, without luck, to find how this behavior is documented, if someone could point me to the right part of the documentation that would also be great.

1条回答
Deceive 欺骗
2楼-- · 2020-03-27 08:02

You are correct. In both of the top functions x in f refers to the parameter x.

There's some considerations with case 3.

In the third example if f isn't defined and you are returning x2 when calling the function it will be equal to whatever x originally was. When you do x = 5; you aren't changing x2. This is because when you assign x2 = x JavaScript makes a copy not a reference.

Unless the x parameter is passed an array or object x2 will be a copy and not a reference of x.

So if you do three(3) then x2 will always be 3 because you're never changing it.

查看更多
登录 后发表回答