function parameter value passing and reference passing in JS:
Before reading this section, it is recommended to refer to section two:
1. The value type can be found in the JavaScript value type section.
2. Reference types can be found in the reference types section of JavaScript .
One. function Pass value type:
The code example is as follows:
function addnum (num) {num+=10; returnvar num=10var result=addnum (num); Console.log (num); Console.log (result);
The above code pop-up values are: 10 and 20, the following analysis:
Declare the variable num and copy it to 10, which is num is a value type, when passing parameters for a function, is to copy this value to the function, so after the function is executed, the value of NUM itself is not changed, the value changed in the function is only a copy.
Two. function passing reference type:
function setName (obj) { obj.name= "Qingdao New sharp"var web= new Object (); Web.name= " Ant Tribe "; setName (web); Console.log (Web.name) ;
The above code popup value is: "Qingdao new Sharp", below carries on the analysis:
Declares an object web, which is a reference type, when passing arguments to a function, is a reference to the Web object being passed, that is, the memory address of the object, so the object that modifies the property in the function is the object itself created outside the function.
Three. Deepen your understanding:
function setName (obj) { obj.name= "Qingdao new sharp"; obj=new Object (); Obj.name= "Ant Tribe"var web=New Object (); SetName (web); Console.log (Web.name) ;
The above code popup value is: Qingdao new Sharp, many people may think will pop up "Ant tribe", below carries on the simple analysis:
Creating an object outside of the function and assigning a reference to the object to the variable Web,web stores the address of the object in memory, and when passing parameters to the function, it is the address of the object that was created outside the function. In the function, create a custom property for the object created outside name and assign a value of "Qingdao new", then create a new object, and assign the address of the new object to obj, this time obj points to not the object created outside the function, so the outer object Name property will not be changed.
The original address is: http://www.softwhy.com/forum.php?mod=viewthread&tid=9052
For more information, refer to: http://www.softwhy.com/javascript/
function parameter value passing and reference passing in JS