内联函数默认参数中变量的范围 [英] Scope of variables inside inline function default parameter

查看:93
本文介绍了内联函数默认参数中变量的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6引入了默认参数。我试图了解内联函数默认参数如何与此新功能一起使用。

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

例如,以下两个函数:

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]

在函数一中, f 保留其自身的关闭范围是否正确?为参数列表中的 x ,因此当函数将x重新定义为新变量时: var x = 5; f 具有的引用与函数内部的引用不同吗?

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.

推荐答案

正确。在 f 中的两个顶级函数 x 中,引用参数 x

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

情况3有一些考虑因素。

There's some considerations with case 3.

在第三个示例中,如果 f 未定义,并且在调用函数时返回 x2 ,它等于任何 x 最初是。当您执行 x = 5; 时,您并没有更改 x2 。这是因为当您分配 x2 = x 时,JavaScript会将副本作为引用。

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.

除非 x 参数传递给 array object x2 将是副本,而不是的引用x

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

因此,如果您执行三(3),则 x2 始终为3,因为您从未更改过它。

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

这篇关于内联函数默认参数中变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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