Javascript函数默认是通过引用还是值返回对象? [英] Does a Javascript function return objects by reference or value by default?

查看:81
本文介绍了Javascript函数默认是通过引用还是值返回对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在函数外部定义了一个对象,在全局范围内。该对象不作为参数传递给函数,但函数会修改它并返回修改后的对象。

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 modified object.

我想知道的是,如果函数返回对象的副本,或原始的全局对象?

What I wanted to know is, if the function returns a copy of the object, or the original global object?

此外,将该对象作为参数传递给函数,会产生影响,因为对象被传递给函数通过引用?

Also, will passing that object to the function as an argument, make a difference, since objects are passed into functions by reference?

推荐答案

每当你返回一个对象时,你都会返回一个对象的引用。同样,当您传递一个对象时,您正在传递一个引用。但是,将对象作为参数传递可以与仅更改全局范围内的对象不同,如这些示例所示。这是因为对象的引用本身是按值传递的。

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.

示例1:

var object = {foo:'original'};

function changeObject() {
    object.foo = 'changed';
    return object;
}

console.log(changeObject()); // outputs {foo:'changed'}
console.log(object); // outputs {foo:'changed'}

示例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.

例3:

var object = {foo:'original'};

function replaceObject() {
    object = {foo:'changed'};
    return object;
}

console.log(replaceObject()); // outputs {foo:'changed'}
console.log(object); // outputs {foo:'changed'}

示例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'}

这篇关于Javascript函数默认是通过引用还是值返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆