javascript how to create reference

后端 未结 5 1668
孤独总比滥情好
孤独总比滥情好 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:41

    Only non-scalar types can be passed as reference, and will always be passed as reference:

    var reference = {};
    my_function(reference);
    console.log(reference); // will show property - a property value
    
    function my_function(my_reference) {
        my_reference.property = "a property value";
    }
    
    var not_a_reference = [];
    my_function(not_a_reference);
    console.log(not_a_reference); // will NOT show 'a value'
    
    function my_function() {
        my_reference.push("a value");
    }
    

    Closer to your example:

    function show(value) {
        alert(value.data);
    }
    
    var value = { 'data': 5 };
    show(value); // alerts 5
    value.data = 6;
    show(value); // alerts 6
    

提交回复
热议问题