Today I answered a question about Javascript, which involves assignment issues, so I want to summarize this issue carefully.
The code copy is as follows:
var a = 'test';
var b = function() {};
ba = 'test';
function change(m, n) {
m = 'change';
na = 'change';
}
change(a, b);
Will the values of variables a and b change after executing the above code?
Original and referenced values
I have introduced the original value and reference value in previous articles. The original value refers to Undefined, Null, Boolean, Number, String, etc., which are stored on the stack, while the reference value is integrated from Object, which is stored in the heap.
Here we need to distinguish the two:
The code copy is as follows:
var a = 'test';
var b = new String('test');
var A = 'true';
var B = new Boolean('true');
For the above four variables, a and A are the original values, while b and B are the reference values.
Assignment mechanism
After clarifying the difference between the original value and the reference value, you can introduce the Javascript assignment mechanism in detail:
In Javascript, each assignment will generate a copy for variables of the original value type, and for referenced values, as its name, it is assigned by reference to the memory of the same storage object.
Assignment of original value:
The code copy is as follows:
var a = 1;//original value
var b = a;// Generate a copy to the variable b
b = 2;//Not related to a
alert(a);//Output 1
Assignment of referenced values:
The code copy is as follows:
var A= new Object();//Reference value
Ax = 1;
var B = A;//Reference assignment, pointing to the same memory
Bx = 2;//Modification of B will affect A
alert(Ax);//Output 2
Parameter pass
Now let’s take a look at how to handle passing two types of values to function parameters at the same time.
1. Pass the original value
The code copy is as follows:
var a = 1;
function test(m) {
m = 2;
}
test(a);
alert(a);//Output 1
The output is 1, so we know that the function just passes the value of the variable in, so m in the function body gets the value 1 and is assigned to 2. This process does not affect the external variable a.
2. Pass the reference value
The code copy is as follows:
var A= new Object();
Ax = 1
function test(M) {
Mx = 2;
}
test(A);
alert(Ax);//Output 2
The output is 2, so we know that the function passes the address of the variable in, so M in the function body gets the passed address. Therefore, when the attribute x is assigned to 2, it will also affect A pointing to the same memory address.
Summarize
Now let’s go back to the opening question:
The code copy is as follows:
var a = 'test';
var b = function() {};
ba = 'test';
function change(m, n) {
m = 'change';
na = 'change';
}
change(a, b);
Variable a is the original value, variable b is the reference value, and one is passed into the function body as a value and the other is the address, so after the function is run, variable a will not change, and the value of variable b will change.