JS对象按值复制与按引用复制 [英] JS object copy by value vs copy by reference

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

问题描述

我正在玩Chrome控制台并注意到一些我无法理解的东西。我知道JS变量是按值复制的,对象是通过引用复制的。下面的代码工作正常,输出2并证明JS对象作为参考:

I was playing with chrome console and noticed something which I couldn't understand. I know in JS variables are copied by value and objects are copied by reference. Below code works fine as expected which outputs 2 and proves JS objects work as reference:

var objA = {a: 1};
var objB = objA;
objA.a = 2; 
objB.a; // 2

但是这段代码不能正常工作。我希望objB.a输出 2 ,但它会给出 1 。为什么?

However this code doesn't work as it should. I expected objB.a to output 2 but it gives 1 instead. Why?

var objA = {a: 1};
var objB = objA;
objA = {a: 2};  //Assigned whole object here instead property.
objB.a; //1 - Shouldn't this be 2 ??


推荐答案

我宁愿将带有对象的变量视为指向对象的指针(比如C指针)而不是引用。

I'd rather think of variables with objects as pointers to objects (like C pointers) rather than references.

在你的第三行,你刚刚更换了 objA ,使其指向另一个对象。它不会改变无论 objB 是指向。

In your third line, you just replaced objA, making it "point to" another object. It does not change whatever objB is "pointing".

第3行, objA 现在指向 {a:2} objB 仍指向 objA 指向您将其分配给<$ c $的时间c> objB ,在第2行, {a:1}

By line 3, objA now points to {a:2} while objB still points to whatever objA was pointing at the time you assigned it to objB, at line 2, which is {a:1}.

line 1: objA -> {a:1}
line 2: objA -> {a:1} <- objB
line 3: objA -> {a:2}, objB -> {a:1}

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

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