Javascript - [为什么?] 将变量分配给对象 [英] Javascript - [Why?] Assigning a variable to an object

查看:60
本文介绍了Javascript - [为什么?] 将变量分配给对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我将变量分配给对象并更改该变量时,它也会更改对象?例如:

Why is it that when I assign a variable to an object and make a change to that variable it also changed the objects? For example:

c = 26;
a = b = c;
a += 1;

a      // 27
b      // 26
c      // 26

但是

z = {};
x = y = z;
x.ab = 5; 

x      // Object {ab: 5}
y      // Object {ab: 5}
z      // Object {ab: 5}

为什么(在上面的例子中)y.abz.ab 存在?我只修改了 x 而不是 yz.为什么在第一个示例中(使用整数),当我更改 a 的值时,bc 没有受到影响?>

Why (in the example above) does y.ab and z.ab exist? I only modified x not y or z. Howcome in the first example (with the integers), when I changed the value of a, b and c weren't affected?

推荐答案

当你将一个对象赋值给一个变量时,它只会引用原始对象,不会复制.所以所有的变量都指向同一个对象.

When you assign an object to a variable, it just makes a reference to the original object, it doesn't make a copy. So all the variables refer to the same object.

这篇关于Javascript - [为什么?] 将变量分配给对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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