When variable a assigns a value to variable B, the value in the stack is copied into the space allocated for the new variable.
How to understand?
Copy Code code as follows:
var x = y = 1;
y = 2;
alert (x);
How much is the value of x?
Copy Code code as follows:
var obj = {};
var sub = {};
sub[' id ' = 3;
Obj[' Sub '] = Sub;
sub[' id ' = 4;
Alert (obj[' Sub '] [' id ']);
What is the value of the obj[' sub ' [' ID ']? Do they really match your expectations?
We ran 2 pieces of code and found that the value of x in the 1th program was unchanged, while the value of the obj[' sub ' [' ID '] in the 2nd program changed. Also is an assignment operation, the same is to modify the value of another copy, why a section of the program source variables have not changed, a section of the program source variable change it? Is this transfer passed by value or by reference?
The answer is given in the second edition of JavaScript Advanced Programming, Li Song translation.
In the first 2 examples, we actually copied the value of a to B, and the difference is, in the first example, the value of a is 1 of the int type, whereas in the second example, the value of a is an address pointer that can access an object, and after copying, the value of B in the 1th example becomes a new int, His value is 1, and in the 2nd example, the value of B becomes the new address pointer, and his value is the address of the object.
The following examples can help you understand
Copy Code code 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 has been invoked to modify the Name property of the variable, the value of Person.name has not changed. This is because the address that obj points to is changed in the function, so modifying the Name property of this address does not affect the Name property of the original address. On the other side, it also confirms that JavaScript is passed by value.