How does variable assignment work in JavaScript?

2019-01-01 07:00发布

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

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

标签: javascript
7条回答
路过你的时光
2楼-- · 2019-01-01 07:37

The difference is between simple types and objects.

Anything that's an object (like an array or a function) is passed by reference.

Anything that's a simple type (like a string or a number) is copied.

I always have a copyArray function handy so I can be sure I'm not creating a bunch of aliases to the same array.

查看更多
登录 后发表回答