传递引用的JavaScript对象 [英] Pass-by-reference JavaScript objects

查看:175
本文介绍了传递引用的JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


请阅读以下代码中的注释,以了解我在尝试
询问的内容。

Please read the comments in the code below to know what I am trying to ask.

预期输出:根据JavaScript中的传递引用机制, objOne 预计会记录 { } 最后,因为 objTwo 是用 {} 初始化的。

Expected Output: As per pass-by-reference mechanism in JavaScript, objOne is expected to log {} at the end, because objTwo was initialized with {}.

var objOne = {
  x: 1,
  y: 2
};

var objTwo = objOne;

// change the x vlaue to 2 by objTwo
objTwo.x = 2;

// Change the value of key x in objOne as well - pass by reference mechanism
console.log(objOne); // { x: 2, y: 2 }

/*** Pass by reference is understood in code, above this comment ***/

// Now what if objTwo initialized with empty object
objTwo = {};

console.log(objOne); // { x: 2, y: 2 } but expected output = {}

// As per pass by reference mechanism. objOne is expected to log {}, because objTwo was initialized with {}.


推荐答案

当你将一个变量分配给另一个变量时,它不是那个这两个变量现在通过引用链接;你误解了通过​​引用传递在这里意味着什么。

When you assign one variable to another, it's not that both those variables are now linked by reference; you're misunderstanding what "pass by reference" means here.

持有对象的变量不会直接持有一个对象。它拥有的是对象的引用。当您将该引用从一个变量分配给另一个变量时,您将复制该引用。现在两个变量都包含对象的引用。通过该引用修改对象会为包含对该对象的引用的两个变量更改它。

A variable holding an object does not "directly" hold an object. What it holds is a reference to an object. When you assign that reference from one variable to another, you're making a copy of that reference. Now both variables hold a reference to an object. Modifying the object through that reference changes it for both variables holding a reference to that object.

当您为其中一个变量分配新值时,您只需修改变量持有的值。变量现在停止持有对象的引用,而是持有其他东西。另一个变量仍保留对原始对象的引用,赋值完全不影响它。

When you assign a new value to one of the variables, you're just modifying the value that variable holds. The variable now ceases to hold a reference to the object, and instead holds something else. The other variable still holds its reference to the original object, the assignment didn't influence it at all.

这篇关于传递引用的JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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