javascript how to create reference

后端 未结 5 1664
孤独总比滥情好
孤独总比滥情好 2021-01-05 20:45

Could you propose any workarounds to implement a reference to variable using closures or any other tricks?

createReference = function() {
    // TODO: how to         


        
5条回答
  •  迷失自我
    2021-01-05 21:34

    In JavaScript, you can't pass primitive values (numbers, strings, etc) by reference. However, every object you pass will always be by reference. (this includes arrays)

    To use your example:

    var foo = { x: 5 };
    var refFoo = foo;
    
    // foo.x => 5
    // refFoo.x => 5
    
    foo.x = 6;
    
    // foo.x => 6
    // refFoo.x => 6
    

提交回复
热议问题