Scope in javascript acting weird

前端 未结 6 1315
悲哀的现实
悲哀的现实 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:04

    The variable 'a' in the context of your function is not the same as the 'a' variable outside the function. This code is semantically equivalent to yours:

    function change(foo,bar) {
        foo.x = 'added';
        foo = bar;//assigning foo as {} to bar
    }
    a={}
    b={}
    change(a,b);
    console.log(a); //expected {} but output {x:'added'}
    console.log(b)
    

    It's obvious in this case that the 'foo' variable only exists inside the function, and doing foo = bar doesn't change a as the reference is passed by value.

提交回复
热议问题