Scope in javascript acting weird

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

    You are right that objects are passed by reference and any change made to the object in the function will be reflected everywhere. This is precisely why adding the x property in the function modified the object outside of it.

    What you are missing is that the line a = b; does not modify the object, it modifies the reference to the object. You can pass both of the objects in another container object / array if you need to set the reference:

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

提交回复
热议问题