Scope in javascript acting weird

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

    This should help to solve your problem:

    var obj = {}, anotherObj = {};
    // in case if they are not global, make them global or define parent scope to be able to modify inside the function
    window.obj = obj;
    window.anotherObj = anotherObj;
    function swap(a, b) {
      window[a].newProp = 'XYZ';
      window[a] = window[b]; // now obj is gone, because replaced with anotherObj
    }
    swap('obj','anotherObj');
    console.log(obj); // now it would give Object {}
    

提交回复
热议问题