Home Web Front-end JS Tutorial How to transfer functions in js

How to transfer functions in js

Jul 16, 2018 pm 04:02 PM

In the process of learning js recently, I encountered the problem of passing objects in js function parameters. I also studied the issues of reference passing and value passing. Although it took some time, I finally understood it.

Data type

Data types in JavaScript can be divided into two categories:

Basic type value primitive type, such as Undefined, Null, Boolean, Number, String.

Reference type value, that is, object type Object type, such as Object, Array, Function, Date, etc.

Copying of variables

As we all know, the basic types and reference types of variables in js are saved in different ways, which results in different variables when copied. If a basic type value is copied from one variable to another variable, the former value will be cloned, and then the cloned value will be assigned 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
Copy after login

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 10s are completely independent. The 10 in num2 is just cloned. It is equivalent to me writing a word document and putting it in the folder of num1. Then I copy the word document and it is called word. Make a copy, and then put this copy in the folder of num2. The two word documents are exactly the same, and modifying either one will not affect both.

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

It can be seen from the above that the value of num2 has been modified, but the value of num1 has not changed. Let’s look at the copying of reference types. When a value of a reference type is copied from one variable to another, a copy of the value stored in the variable object is also copied into 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
Copy after login

The result printed out for the first time is "111", which is easy for us to understand, but the result printed out the second time is "222", which is a bit puzzling. This is the difference between reference types and basic types. When copying an object, an identical object will not be created in the heap memory. It will just have an additional variable that holds a pointer to the object. Copy the value of obj1 to obj2, and the copy of this value is actually a pointer. This pointer points to an object stored in the heap. That is to say, a new memory address is created and passed to obj2, obj1 and obj2. The variables point to the same Object at the same time. When the object is changed, their values ​​​​will change, which means that changes made by any one of them will be reflected in the other. The simplified diagram below may be more clear.

Passing of function parameters

"JS Advanced Programming" describes parameter passing like this: All function parameters are passed by value, that is to say, the parameters outside the function are Copying the value to the parameter inside the function is the same as copying the value from one variable to another. So if you can understand the copying of variables, then the passing of parameters will be very simple. Let’s start with an example of basic types.

var count = 10;function num(num1){
   num1 = 1;
   return num1;
}var result = num(count);console.log(result);//1
console.log(count);//10,并未变成1
Copy after login

This example is easy to understand. It actually creates a copy of count, and then passes the value of count into the parameter. Because the value of the parameter is defined in the function, 1 overwrites 10. Finally The result returns 1, but the count has not changed. Let's look at 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
Copy after login

In the above example, person is copied and passed into obj(). peo and person point to the same object, and modifying the name attribute in peo actually modifies the object they jointly point to. The name attribute and the name attribute referenced by the corresponding external person also change, so the printed one is Jerry. In fact, at first glance, it seems that reference type parameters are passed by reference. This was the mistake I made initially. Let’s look at 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
Copy after login

In the above example, an object is redefined in the function, that is, there are now two objects in the heap memory. The external person points to the old object. After the parameters are passed in Points to the newly defined object, so the value returned after the call is the value of the newly defined object. If the parameters are passed by reference, then the printed result of person.name is Jerry. From this point, it can be concluded that the parameters are passed by value (some places call it passed by sharing).

We used "A Brief History of Humanity" recommended by Lao Luo to visualize it, but the description is not very good. The title of the first chapter of the brief history is "Cognitive Revolution". We changed its name to "person". According to the number of pages behind, we can directly find the content of "Cognitive Revolution" "that is, the object pointed by peoson". Second The chapter is "Agricultural Revolution", we call it "result", and its sub-directory has a section "Memory Overload" (renamed "peo"). You can also find the content of this section directly based on the page number. Now we copy "person" to "peo", the "peo" section in Chapter 2 becomes "person", and what we find based on "peoson" in Chapter 1 is still the one in Chapter 1 Content, this is because they point to different content sections and do not interfere with each other. Here, the heap memory is the content of each chapter, and the content of Chapter 1 and Chapter 2 are two different objects, and the two are unrelated to each other, so when printing external person.name, the result is still the previous object attribute value.

in conclusion

In short, parameters in js are passed by value. The examples I wrote are a bit rough, but the examples in "JavaScript Advanced Programming" are more clear and easier to understand.

Related recommendations:

The implementation principle of function parameters in js

The actual parameters, formal parameters and Understanding closure

The above is the detailed content of How to transfer functions in js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles