var a = {N:1}; var B = A; Hold A to check back a.x = a = {N:2}; alert (a.x);// -undefined alert (b.x);/--{N:2}
For this code, most people understand this: ======== wrong understanding =======
For a.x = a = {n:2}
Most people, the idea should be:
{n:2}
assign a value to a first
- Then create the a.x and assign the
{n:2}
value to a.x
It does not seem to be true that the value of a.x is undefined, because a.x is definitely assigned.
But in fact, the value of a.x is undefined.
Take a look at this: then a = a.x = {n:2}
, as the original idea should be:
- Give the
{n:2}
assignment to a.x first, then it's the equivalent b.x = {n:2}
.
- Re-point a again
{n:2}
. Then this is the value of the post-a.x is indeed the Undefined,a object {n:2}
There is no x attribute.
According to this idea, the results of the above two methods should be different. But the truth is a = a.x = {n:2}
the a.x = a = {n:2}
same as the result. So obviously this is not the right idea.
=========================== correct understanding of this is the ===================
After the parser accepts a = a.x = {n:2}
such a statement, it does this:
- Find pointers to a and a.x. If you already have a pointer, do not change it. If there is no pointer, that variable is not declared yet, create it and point to null.
A is a pointer, pointing {n:1}
; a.x is not a pointer, so create it, point to null.
- Then the pointer found above points to the rightmost assigned value, that is
{n:2}
.
So after the execution, there is the following variable diagram. We can slowly realize, figured out is very simple.
If you feel that this understanding is more difficult, you can first understand the following way, and then come to see the above explanation
The assignment is from right to left, but don't get dizzy, it's really simple, from the 运算符优先级
thought of
a.x = a = {n:2};
.
Operations take precedence =
over assignment operations, so the assignment here can be understood as
- Declares the X attribute in a object, which is used to assign a value, at which point B points to a and has an unassigned x attribute
- Assigns a value to the A object, at which point the variable name a changes to the object {N:2}
- For the x attribute in step 1, which is the X property of the object, or the X property of B to the object, assign a value
Assignment Result:
2}b => {n: 1, x: {n: 2 } }
JavaScript hyphen Assignment Problem (this is a problem from Segmentfault)