Javascript的赋值操作是复制引用吗? [英] Javascript's assignment operation is to copy references?

查看:65
本文介绍了Javascript的赋值操作是复制引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本示例:

var b = 10;
var c = b;
b++;
console.log(b,c);

>> 11 10

c 看起来像是 b 的副本.

但是在另一种情况下:

var x = {};
var y = x;
x.abc = 10;
console.log(x.abc, y.abc);

>> 10 10

为什么 y 不是 x 的副本,而是指向同一实例 x 的引用?

Why is the y not a copy of x, but a reference which points to the same instance x points to?

此外,我猜想 b ++ 创建了另一个实例,因此 b 指向新实例,而 c 指向旧实例.但是...

Also, I guessed b++ creates another instance, so b points to the new instance but c points to the old one. However...

var u = 10;
setTimeout(function() {
  console.log(u);
}, 10000)
u++;

>> 11

如果 u ++ 创建一个新实例,那么匿名函数内的 u 应该指向旧的 u ,不是吗?

If u++ creates a new instance, then the u inside the anonymous function should point to the old u, shouldn't it?

推荐答案

c 看起来像是 b 的副本.

两者都是对相同的不可变值的引用.

Both are references to the same immutable value.

为什么 y 不是 x 的副本,而是指向实例 x 的引用所指向的引用?

Why the y is not copy of x but a reference which points to the instance x points to?

x 首先是对对象的引用,因此 y 是它的副本(引用的副本,而不是对象的副本)

x was a reference to an object in the first place, so y is a copy of it (a copy of the reference, not a copy of the object).

如果 u ++ 创建了新实例,

不是.

匿名函数中的 u 应该指向旧的 u ,不是吗?

the u in anonymous function should points to the old u, shouldn't it?

u ++ 将对11的引用分配给 u .匿名函数正在查看 u ,而不是创建函数时 u 的值".

u++ assigns a reference to 11 to u. The anonymous function is looking at u and not "the value of u at the time the function was created".

这篇关于Javascript的赋值操作是复制引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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