You're confusing objects with references.
An array is an object, when you use a literal like [1,2,3]
you're making a new array.
A variable name like this
or a
is a reference to an object. If it helps, imagine an object as a person, and the reference as their nickname. You can have more than one reference to the same object, for example:
var a = [1,2];
var b = a;
b.push(3);
alert(a.length); // Gives "3"
Imagine if you had a friend named Sarah. You also sometimes call her "Ace". If Sarah gets a haircut one day, Ace has a haircut too, because "Sarah" and "Ace" are both different names for the same person.
If you use a mutating array method like a.push
or a.splice
(concat
however is not one!), you change the existing Array object, and a
still refers to the same object. This is like getting a hair cut - you may look different, but you're still the same person.
When you assign a reference to a new value, with a = [1,2,3]
, you're creating a new array, and changing a
to refer to it. This is like finding a new friend with different hair, and deciding to call her Ace instead.
Now this
is a special name generated by Javascript. It's not a given name like Sarah, but more of a title, like "mother". Your mother can get a new haircut, but you can't get a new mother. Likewise, you can't change what this
refers to from inside a function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…