Understand the parameter transfer in JS function through an example

Time:2019-10-31

First look at a JS written test:


var setObj=function(o){
o.name="xiaoming";
o={};
o.name="xiaohong";
}
var p={name:"xixi",age:24};
setObj(p);
console.log(p);

The answer is {Name: Xiaoming, age24};

In JavaScript, the function parameter defaults to the reference type.

1. Function transfer value type:

The code example is as follows:


function addNum(num){
 num+=10;
 return num;
}
var num=10;
var result=addNum(num);
console.log(num);
console.log(result);

The pop-up values of the above codes are: 10 and 20, and the following analysis is carried out:

Declare the variable num and copy it to 10. This is a value type. When passing parameters to a function, copy the value to the function. Therefore, after the function is executed, the value of num itself is not changed, and the changed value in the function is only a copy.

2. Function transfer reference type:

function setName(obj){ 
Obj. Name = "Qingdao new generation"; 
} 
var web=new Object(); 
Web. Name = "ant tribe";
 setName(web); 
console.log(web.name);

The pop-up value of the above code is “Qingdao new sharp”, and the following analysis is carried out:

Declare an object web, which is a reference type. When passing parameters for a function, it is the reference of the passed web object, that is, the memory address of the object. Therefore, the object modifying properties in a function is the object created outside the function itself.

3. Deepen understanding:

function setName(obj){ 
 Obj. Name = "Qingdao new generation"; 
 obj=new Object(); 
 Obj. Name = "ant tribe"; 
 } 
 var web=new Object(); 
setName(web); 
console.log(web.name);

The pop-up value of the above code is: Qingdao new generation, many people may think that “ant tribe” will pop up. Here is a simple analysis:

Create an object outside the function, and assign the reference of the object to the variable web. What is stored in the web is the storage address of the object in memory. When passing parameters for the function, it is the address of the object created outside the function. In the function, create a custom attribute name for the object created outside and assign it as “Qingdao new sharp”, then create a new object and assign the address of the new object to obj. At this time, obj does not point to the object created outside the function, so the name attribute of the external object will not be changed.

It is hard for programmers in other languages to accept such writing. We should avoid such writing in actual development, because it will cause global scope pollution. Recently, I encountered the problem of JS delivery mode when reading “JavaScript advanced programming”. It took some time, but I finally understood.

data type

In JavaScript, data types can be divided into two types:

  • Basic type values, such as undefined, null, Boolean, number, string.
  • Reference type value, that is, object type, such as object, array, function, date, etc.

Replication of variables

As we all know, the basic type and reference type of variables in JS are saved in different ways, which leads to different variable replication. If you copy a value of basic type from one variable to another, you will clone the value of the former, and then assign the cloned value to the latter. Therefore, the two values are completely independent, but their values are the same.


var num1 = 10;
var num2 = num1;
console.log(num2);//10

The value saved in num1 above is 10. When the value of num1 is assigned to num2, the value of num2 is also 10. But these two 10’s are completely independent. The 10’s in num2 are just cloned, which is equivalent to that I wrote a word document, put it in the folder of num1, and then I copy the word document, which is called word copy, and then put the copy in the folder of num2. The two word documents are exactly the same, and any modification will not affect the two.


num2 += 1;
console.log(num1); //10
console.log(num2); //11

It can be seen from the above that the value of num2 is modified, and the value of num1 does not change. Let’s look at the replication of reference types. When you copy a reference type value from one variable to another, the value stored in the variable object is also copied and placed in the space allocated for the new variable.


var obj1 = {
name : "111"
};
var obj2 = obj1;
console.log(obj2.name); //111
obj2.name = "222";
console.log(obj1.name); //222

The first printing result is “111”, which is easy for us to understand, but the second printing result is “222”, which is a little confusing. This is the difference between reference types and base types. When you copy an object, you do not generate a new object in the heap memory, but save a variable that points to this pointer. Copy the value of obj 1 to obj 2, and the copy of the value is actually a pointer. The pointer points to an object stored in the heap, that is to say, a new memory address is created and passed to obj 2. Two variables obj 1 and obj 2 point to the same object at the same time. When changing the object, their values will change, that is, any changes they make. Changes are reflected in the other. The following simple diagram may be clearer.

Transfer of function parameters

“JS advanced programming” describes parameter transfer as follows: all function parameters are passed by value, that is to say, copying the value outside the function to the parameter inside the function is the same as copying the value from one variable to another. So if you can understand the replication of variables, then the transmission of parameters is very simple. Let’s give an example of the basic types first.

var count = 10;
function num(num1){
num1 = 1;
return num1;
}
var result = num(count1);
console.log(result);//1
Console.log (count); // 10, not 1

This example is easy to understand. In fact, a copy of count is created, and the value of count is passed into the parameter. Because the value of the parameter is defined in the function, 1 will overwrite 10, and the final result will return 1, but the count has not changed. See an example of passing objects.


var person = {
name : "Tom"
};
function obj(peo){
peo.name = "Jerry";
return peo;
}
var result = obj(person);
console.log(result.name);// Jerry
console.log(person.name);// Jerry

In the above example, copy person into obj(), PEO and person point to the same object, and modify the name attribute in PEO, in fact, modify the name attribute of the object they point to together, and the name attribute referenced by the corresponding external person changes, so the printed one is Jerry. In fact, at first glance, it seems that the parameters of reference type are passed by reference, which is my initial mistake. Let’s take another example.


var person = {
name : "Tom"
}; 
function obj(peo){
peo = {
name : "Jerry"
};
return peo;
}
var result = obj(person);
console.log(result.name);// Jerry
console.log(person.name);// Tom

In the above example, an object is redefined in the function, that is, there are two objects in the heap memory now. The external person points to the old object, and the new object is pointed to after the parameter is passed in, so the value returned after the call is the value of the new object. If the parameter is passed by reference, the result printed by person.name is Jerry. From this point, it can be concluded that the parameter is passed by value (in some places, it is called passing by share).

We take Lao Luo’s “brief history of human beings” to visualize it, which is not very well described. In the first chapter of the brief history, the title is “cognitive revolution”. We can directly find the content of “cognitive revolution” by changing its name to “person” according to the number of pages. In the second chapter, “agricultural revolution”, we call it “result”. There is a section of “memory overload” (renamed “PEO”) in its sub catalogue, which can also be directly based on Page to find the section.

Now we copy “person” into “PEO”. The section of “PEO” in Chapter 2 becomes “person”, and what we find according to “peoson” in Chapter 1 is the content of Chapter 1, because they point to different content plates and do not interfere with each other. Here, heap memory is the content of each chapter, while the contents of Chapter 1 and Chapter 2 are two different objects, which are irrelevant. Therefore, when printing external person.name, the result is still the property value of the previous object.

conclusion

All in all, parameters are passed by value in JS. I’ve written rough examples, and the examples in JavaScript advanced programming are clearer and easier to understand.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.