All function parameters in ecmascript are passed by value. That is to say, the external value of the function is copied to the internal parameter of the function.
The same as copying a value from one variable to another. The transfer of the basic type value is the same as the replication of the basic type variable.
The transfer of the reference type value is the same as the copy of the reference type variable. Many developers may be confused about this, because
For access variables, there are two methods: value-based and reference-based, and parameters can only be passed by value.
When you pass a value of the basic type to a parameter, the passed value is copied to a local variable (that is, a named parameter, or
Ecmascript is an element in the arguments object.
This value is copied to a local variable from the address in the memory. Therefore, changes to this local variable are reflected outside the function.
function setName(obj) {obj.name = "Nicholas";}var person = new Object();setName(person);alert(person.name); //"Nicholas"
In the above Code, create an object and save it in the variable person. Then, the variable is passed to setname ()
The function is copied to OBJ. In this function, OBJ and person reference the same object. In other words, that is
This variable is passed by value. OBJ also accesses the same object by reference. Therefore, when you add name for OBJ in the function
After the property, the person outside the function will also be reflected; because the person points to only one object in the heap memory and is full
Bureau object. Many developers mistakenly think that the objects modified in the local scope will be reflected in the global scope.
Parameters are passed by reference. To prove that the object is passed by value, let's take a look at the modified example below:
function setName(obj) {obj.name = "Nicholas";obj = new Object();obj.name = "Greg";}var person = new Object();setName(person);alert(person.name); //"Nicholas"
The only difference between this example and the previous example is that two lines of code are added to the setname () function: one line of code is obj.
A new object is defined, and another line of code defines a name attribute with different values for this object. When the person is passed
After setname (), its name attribute is set to "Nicolas ". Then, a new object is assigned to the variable OBJ and its name is
Set the property to "Greg ". If a person is passed by reference, the person will be automatically changed to its name attribute value.
Is a new object of "Greg. However, when you access person. name again, the displayed value is still "Nicolas ". This description
The original reference remains unchanged even if the parameter value is modified inside the function. In fact, when you override OBJ in the function
Variables reference a local object. This local object will be destroyed immediately after the function is executed.
S1: Passing Parameters