Many developers usually ignore these small issues, but we need to understand them again. because a friend asked me today, I wrote it here. in C #, we know that if we want to pass the parameter type to a function as an object, array or other reference type. actually upload... syntaxHighlighter. all ();
Many developers usually ignore these small questions, but we need to understand them again. Because a friend asked me today, I wrote it here,
In C #, we know that if you want to pass the parameter type to a function as an object, array or other reference type.
Actually, the object address is passed in the past.
So what is the difference in javascript? Below we need to prove through examples.
Var par1 = 1; // number (value type)
Var par2 = []; // array (reference type)
Var par3 = {}; // object (reference type)
Function Test (par1, par2, par3 ){
Par1 = 3;
Par2 = [1, 2, 3];
Par3 = {a: 1 };
}
Test (par1, par2, par3 );
Alert (par1); // output 1
Alert (par2); // blank output
Alert (par3.a); // output undefined. In the above Code, we first define the value type par1, reference type par2, par3, and pass it into the Test function.
However, par2 and par3 output the previous data.
Does it mean that if the reference type is introduced when a function is called, it is actually a transfer value? Actually not.
Array, object, and other reference types are also passed by value, but here the value refers to the value of the variable address
In the previous example, when we pass par2 and par3 into the function, we actually have a copy of the address, which is the same as the address of par2 and par3 outside.
However, we assigned a value for par2 and par3 and changed the address direction, so the address points to the new object and array. in this case, the internal and external par2 and par3 do not point to the same address.
To prove this problem, we can try to directly use our own objects without assigning values to them. The Code is as follows:
Var par1 = 1; // number (value type)
Var par2 = []; // array (reference type)
Var par3 = {}; // object (reference type)
Function Test (par1, par2, par3 ){
Par1 = 3;
Par2.push (10); // operate on its own object
Par3.a = 2; // operate on its own object
}
Test (par1, par2, par3 );
Alert (par1); // output 1
Alert (par2); // output 10
Alert (par3.a); // output 2 facts show that when we call a function to pass in a value type parameter, we pass in a value. When we pass in a value of the reference type, we pass in, is their address.