The way of the function in JavaScript is more wonderful;
JavaScript does not pass parameters by reference, not strictly all by value, but for reference types, the individual feels like a shared pass
The base type is passed into the function as a parameter (just copy the value to a local variable inside the function)
var a = 10;
function foo (a) {
A = 20;
return A;
}
Console.log (foo (a)); 20
Console.log (a); 10
For a primitive type it is simply a local variable that assigns a value to the inside of the function, so the value modified in the local scope is not reflected in the global variable, and when we look at the reference type here, many people will misunderstand the next generation code.
var obj = {
Name: "ZP"
};
function foo (obj) {
Obj.name = "Zpy";
return obj;
}
Foo (obj);
Console.log (Obj.name); "Zpy"
Many people think that this example is not the local scope of the modified value and reflected in the global variable (so that there is said JS in the conclusion by reference), but in fact it is not so, in JavaScript object name can also be understood as a pointer, when the reference type as a parameter to pass the function, The address is also copied to the local variables inside the function, which means that the local variable of the function and the global variable obj point to the same object in the heap memory.
Look at the following section of the code can be explained that JS is not passed by reference
var obj = {
Name: "ZP"
};
function foo (obj) {
obj = new Object ();
Obj.name = "Zpy";
return obj;
}
Foo (obj);
Console.log (Obj.name); "ZP"
obj = new Object () the address name in the local variable is changed, the local variable is destroyed after the function is executed, so it can be confirmed that JS is not passed by reference
This article is from the "zp1996" blog, make sure to keep this source http://9865481.blog.51cto.com/9855481/1687693
JavaScript function Pass Parameter