变量赋值如何在JavaScript中工作? [英] How does variable assignment work in JavaScript?

查看:69
本文介绍了变量赋值如何在JavaScript中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我前几天正在玩,只是为了确切了解批量作业在JavaScript中是如何运作的。

So I was playing around the other day just to see exactly how mass assignment works in JavaScript.

首先我在控制台中尝试了这个例子:

First I tried this example in the console:

a = b = {};
a.foo = 'bar';
console.log(b.foo);

结果是栏显示在警报中。这是公平的, a b 实际上只是同一对象的别名。然后我想,我怎么能让这个例子变得更简单。

The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.

a = b = 'foo';
a = 'bar';
console.log(b);

这几乎是一回事,不是吗?那么这一次,它返回 foo 而不是 bar 正如我对第一个例子的行为所期望的那样。

That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.

为什么会发生这种情况?

Why does this happen?

NB 这个例子可以通过以下内容进一步简化代码:

N.B. This example could be simplified even more with the following code:

a = {};
b = a;
a.foo = 'bar';
console.log(b.foo);

a = 'foo';
b = a;
a = 'bar';
console.log(b);

(我怀疑JavaScript将字符串和整数等原语与哈希值区别对待。哈希值返回指针而核心原语返回他们自己的副本)

(I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)

推荐答案

在第一个示例中,您要设置现有对象的属性。在第二个示例中,您要分配一个全新的对象。

In the first example, you are setting a property of an existing object. In the second example, you are assigning a brand new object.

a = b = {};

a b 现在指向同一个对象。所以当你这样做时:

a and b are now pointers to the same object. So when you do:

a.foo = 'bar';

它设置 b.foo 以及 a b 指向同一个对象。

It sets b.foo as well since a and b point to the same object.

然而!

如果你这样做:

a = 'bar';

你说 a 指向a现在不同的对象。这对之前指向的 a 没有影响。

you are saying that a points to a different object now. This has no effect on what a pointed to before.

在JavaScript中,分配变量并分配属性是2种不同的操作。最好将变量视为对象的指针,当您直接赋值给变量时,您不会修改任何对象,只是将变量重新分配给不同的对象。

In JavaScript, assigning a variable and assigning a property are 2 different operations. It's best to think of variables as pointers to objects, and when you assign directly to a variable, you are not modifying any objects, merely repointing your variable to a different object.

但是分配属性,如 a.foo ,将修改 a 指向的对象。当然,这也会修改指向此对象的所有其他引用,因为它们都指向同一个对象。

But assigning a property, like a.foo, will modify the object that a points to. This, of course, also modifies all other references that point to this object simply because they all point to the same object.

这篇关于变量赋值如何在JavaScript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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