Javascript assignment mechanism details

  • 2020-03-30 04:24:15
  • OfStack

Today I answered a question about Javascript that involves assignment, so I want to wrap it up nicely.


var a = 'test';
var b = function() {};
b.a = 'test';
function change(m, n) {
    m = 'change';
    n.a = 'change';
}
change(a, b);

Will the values of variables a and b change after executing the above code?

Original and reference values

In previous articles, original values and reference values were introduced. Original values refer to Undefined, Null, Boolean, Number, String, etc., which are stored in the stack, while reference values are integrated from Object, which is stored in the heap.
Here's the difference:


var a = 'test';
var b = new String('test');
var A = 'true';
var B = new Boolean('true');

Above four variables, a and a are original values, and b and b are reference values.

Assignment mechanism

Once you know the difference between the original value and the reference value, you can specifically introduce the Javascript valuation mechanism:

In Javascript, each assignment generates a copy for a variable of the original value type, while a reference value, as its name implies, is assigned by reference to the same stored object in memory.
Assignment of the original value:


var a = 1;//Original value
var b = a;//Generate a copy to the variable b
b = 2;//It's independent of a
alert(a);//Output 1 < br / >

Assignment of reference value:


var A= new Object();//Reference value
A.x = 1;
var B = A;//Reference assignment, pointing to the same place in memory
B.x = 2;//Modifying B will affect A
alert(A.x);//Output 2 < br / >

Parameter passing

Now let's look at what happens when you pass two types of values to a function parameter.
1. Pass the original value


var a = 1;
function test(m) {
    m = 2;
}
test(a);
alert(a);//Output 1 < br / >

The output is 1, so we know that the function is just passing in the value of the variable, so the m in the function gets the value 1, which is then assigned to 2, and that doesn't affect the external variable a.

2. Pass the reference value


var A= new Object();
A.x = 1
function test(M) {
    M.x = 2;
}
test(A);
alert(A.x);//Output 2 < br / >

The output is 2, so we know that the function passed in the address of the variable, so the M in the function gets the address passed in, so when the property x is assigned A value of 2, it also affects the A that points to the same memory address.

conclusion

Now back to the question at the beginning:

The same code at the page code block index 0

Variable a is the original value, variable b is the reference value, passed into the function body, one is the value, one is the address, so after the function runs, the variable a will not change, but the value of variable b will change.


Related articles: