Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
92 views
in Technique[技术] by (71.8m points)

How does variable assignment work in 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);

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);

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?

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);
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 and b are now pointers to the same object. So when you do:

a.foo = 'bar';

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

However!

If you do this instead:

a = 'bar';

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...