When variable A is assigned to variable B, the value in the stack is copied to the space allocated for the new variable.
How to Understand?
Copy codeThe Code is as follows:
Var x = y = 1;
Y = 2;
Alert (x );
What is the value of x?
Copy codeThe Code is as follows:
Var obj = {};
Var sub = {};
Sub ['id'] = 3;
Obj ['sub'] = sub;
Sub ['id'] = 4;
Alert (obj ['sub'] ['id']);
What is the value of obj ['sub'] ['id? Are they really in line with your expectations?
We run two pieces of code separately and found that the value of x in the 1st segment program has not changed, but the value of obj ['sub'] ['id'] in the 2nd segment program has changed. It is also a value assignment operation and another copy value. Why does a program source variable remain unchanged? Is the transfer passed by value or by reference?
The answer is provided in the second edition of JavaScript advanced programming design translated by Li songfeng.
In the first two examples, the value of A is actually copied to B. The difference is that in the first example, the value of A is 1 of the int type, in the second example, the value of A is an address pointer, which can access an object. After copying, the value of B in the second example is changed to A new int, his value is 1, and in the 2nd example, the value of B is changed to a new address pointer, and his value is the address of this object.
The following example can help you understand
Copy codeThe Code is as follows:
Function setName (obj ){
Obj. name = "test1 ";
Obj = {};
Obj. name = "test2 ";
}
Var person = new Object ();
SetName (person );
Alert (person. name );
As you can see, although the setName function is called to modify the name attribute of the variable, the value of person. name has not changed. This is because in the function, the address pointed to by obj is changed, so modifying the name attribute of this address does not affect the name attribute of the original address. On the other hand, it also proves that JavaScript is passed by value.