Does a Javascript function return objects by reference or value by default?

后端 未结 5 889
粉色の甜心
粉色の甜心 2020-12-30 23:24

I have an object defined outside the function, in a global scope. This object is not passed into the function as an argument, but the function does modify it and return the

5条回答
  •  死守一世寂寞
    2020-12-31 00:01

    From your question this is how I think your code looks (more or less):

    var o = {};
    
    function f() {
        o.prop = true;
        return o;
    }
    
    1. In this case the global variable o references an object.
    2. When you modify o you're modify whatever o references. Hence it modifies the original object.
    3. When you return o you're returning a reference to the original object.

    Passing the object to a function results in the reference to the original object being passed. Hence any modifications will affect the original object. For example:

    var o = {};
    
    f(o);
    
    console.log(o.prop); // true
    
    function f(o) {
        o.prop = true;
    }
    

提交回复
热议问题