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

后端 未结 5 858
粉色の甜心
粉色の甜心 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-30 23:49

    Whenever you're returning an object, you're returning a reference to the object. Likewise, when you're passing an object, you're passing a reference. However, passing an object in as an argument can be different than just changing an object in global scope, as these examples show. This is because the reference to the object is itself passed by value.

    If you're changing the members of an object, then whether you pass it in as an argument or just update the global object makes no difference. Either way, you're working with the same object.

    Example 1:

    var object = {foo:'original'};
    
    function changeObject() {
        object.foo = 'changed';
        return object;
    }
    
    console.log(changeObject()); // outputs {foo:'changed'}
    console.log(object); // outputs {foo:'changed'}
    

    Example 2:

    var object = {foo:'original'};
    
    function changeArgument(object) {
        object.foo = 'changed';
        return object;
    }
    
    console.log(changeArgument(object));  // outputs {foo:'changed'}
    console.log(object);  // outputs {foo:'changed'}
    

    On the other hand, if you're overwriting the object with a new object, the change won't persist if you do it to the argument, but will persist if you do it to the global object. That's because the argument passes the reference to the object by value. Once you replace this value with a reference to a new object, you're not talking about the same object anymore.

    Example 3:

    var object = {foo:'original'};
    
    function replaceObject() {
        object = {foo:'changed'};
        return object;
    }
    
    console.log(replaceObject()); // outputs {foo:'changed'}
    console.log(object); // outputs {foo:'changed'}
    

    Example 4:

    var object = {foo:'original'};
    
    function replaceArgument(object) {
        object = {foo:'changed'};
        return object;
    }
    
    console.log(replaceArgument(object)); // outputs {foo:'changed'}
    console.log(object); // outputs {foo:'original'}
    

提交回复
热议问题