If re-declaration with var will have effect on existed variable

后端 未结 2 1014
名媛妹妹
名媛妹妹 2020-12-11 19:39



        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 20:21

    Why the results of show2 and show3 are different.

    let's evaluate your code by this way

    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})
    

提交回复
热议问题