如果用var重新声明将对现有变量产生影响

BAK*_* ZQ 5 javascript ecmascript-6

const show1 = function(x, y = () => {x = 2; return x;}) {
    let x = 3;
    console.log(y());
    console.log(x);
};
show1();
Run Code Online (Sandbox Code Playgroud)

const show2 = function(x, y = () => {x = 2; return x;}) {
    x = 3;
    console.log(y());
    console.log(x);
};
show2();
Run Code Online (Sandbox Code Playgroud)

const show3 = function(x, y = () => {x = 2; return x;}) {
    var x = 3;
    console.log(y());
    console.log(x);
};
show3();
Run Code Online (Sandbox Code Playgroud)

输出

show1: Uncaught SyntaxError: Identifier 'x' has already been decalred;
show2: 2 2
show3: 2 3
Run Code Online (Sandbox Code Playgroud)

我被告知,存在一个临时的死区,其中声明并初始化了参数变量。请参阅https://exploringjs.com/es6/ch_variables.html#sec_parameters-as-variables。因此,这里有两个范围,一个是参数范围,另一个是函数范围。

  1. 从show1中的错误中,我认为x此函数中已经声明了一个变量。
  2. 根据重新声明一个javascript变量。重新声明不会对x(使用var)做任何事情。为什么结果show2show3不同。

我在此处发布了相同的问题,如果变量在函数执行开始时就已经声明,并且被屏蔽为重复项。但是我找不到任何有用的疑问。

deg*_*egr 1

Why the results of show2 and show3 are different.

让我们通过这种方式评估你的代码

const show2 = function(x, y = () => {x.value = 2; return x;}) {
    x = {name: "from argument", value: 3};
    console.log(y());//{name: "from argument", value: 2}
    console.log(x);//{name: "from argument", value: 2}
};
show2();

const show3 = function(x, y = () => {if(!x){x = {name:"from function", value: -1}}x.value = 2; return x;}) {
    var x = {name: "from var", value: 3};
    console.log(y());//{name: "from function", value: 2}
    console.log(x);//{name: "from var", value: 3}
};
show3();

const show4 = function(x, y = () => {if(!x){x = {name:"from function", value: -1}}x.value = 2; return x;}) {
    var x = {name: "from var", value: 3};
    console.log(y());//{name: "from outside", value: 2}
    console.log(x);//{name: "from var", value: 3}
};
show4({name:"from outside", value: -1})
Run Code Online (Sandbox Code Playgroud)