Scope in javascript acting weird

前端 未结 6 1301
悲哀的现实
悲哀的现实 2021-02-18 18:47

Object are passed with their reference in javascript. Meaning change in that object from any where should be reflected. In this case, the expected output was {} for console.log(

6条回答
  •  离开以前
    2021-02-18 19:22

    If you added another line you can get a clearer picture of what is happening:

    function change(a,b) {
        a.x = 'added';
        a = b;
        a.x = 'added as well';
    };
    a={};
    b={};
    change(a,b);
    console.log(a);  //{x:'added'}
    console.log(b);  //{x:'added as well'}
    

    When you're doing a = b you're assigning the local variable a to the reference that b is holding.

提交回复
热议问题