Js return value problem
Today I saw an article on the Internet about the return value of JS functions. There are some difficulties in JS functions. I mentioned it above about the issue of js function returning another function, and attached an interview question. I will share it with you
[javascript] view plain copy var add = function(x){ var sum = 1; var tmp = function(x){ sum = sum + x; return tmp; } tmp.toString = function(){ return sum; } return tmp; } // alert(add(1)(2)(3)) --> 6
Next, let’s explain in detail the return of another function. The problem.
Actually, I came from Java. When I first saw that article, I didn’t know much about returning another function. The reason why I wrote this article was because there was a little bit of confusion in it. I feel strange, that is the final calling method
[javascript] view plain copy
add(1)(2)(3)
Because in java, I I have never seen such a function calling method, so it caught my attention, and I decided to research it. I will share my research below. Of course, if you already have a deep understanding of this, you can choose to skip it. Or give pointers and smile when there are deficiencies. Okay, without further ado, let’s get to the point.
Let's look at the simplest example:
[javascript] view plain copy function create1(pro) { console.log("pro : " + pro); return function(obj1, obj2){ console.log(obj1 + " -- " + obj2); return obj1 + obj2; } }
I built a simple function create1, and it has a return value, and the return value is an internal function. After the function is built, let’s call it next:
[javascript] view plain copy var c1 = create1("pro"); // 创建函数
If according to my previous understanding, when I call this method, pro: pro should be printed, and then an error will be reported. If you have the same thoughts as me after reading this, then congratulations on thinking too much or having a fixed mindset. Smile
. What is true is that when we call it through the above code, the log prints pro : pro , but no error is reported, and after we call it repeatedly, we just print the same log back and forth. This also means that at this time, it only entered the create1() method and did not enter the internal function of the function. Inspired by the interview questions, I tried to call it once and found that the subsequent results were printed.
[java] view plain copy c1(1, 2); // 调用函数
The following log is printed; this shows that when we first call the method, we did not actually enter the inner function, but only entered the outer function body. We only have to Only by calling can we enter the inner function body, and at this time, if we repeat the above call, it will only call the inner function body, and there will be no outer function body.
A function like this returns another function. Our first call only builds an outer function body Object. Only subsequent calls can call the inner function body. And repeated calls will only repeat the inner function body.
Don’t worry, it’s not over yet, there will be more to come...
Next, let’s take a look at another situation. We first declare a function to do addition operations:
[javascript] view plain copy function infun(obj1, obj2) { console.log(obj1 + " -- " + obj2); return obj1 + obj2; } 然后再声明一个函数,在该函数中调用上面声明的函数: [javascript] view plain copy function create2(pro) { console.log("pro = " + pro); return infun(obj1, obj2); // 这个时候,会报错 }
Finally, call:
[javascript] view plain copy var c1 = create2("pro");
Check the log:
pro = pro Uncaught ReferenceError: obj1 is not defined
You will find that after a log is printed, an exception is thrown. Make some changes to the method. When
[javascript] view plain copy function create2(pro) { console.log("pro = " + pro); var obj1 = 1, obj2 = 2; return infun(obj1, obj2); // 这个时候,会报错 }
is called, it will be found to run normally and two log records will be printed.
This shows that, similar to this, returning a declared function within a function is actually calling the declared function, which is different from the above situation.
Okay, now look back and take a closer look at the interview questions at the beginning, and you will find that everything is clear:
[javascript] view plain copy // 声明一个函数表达式 var add = function(x){ var sum = 1; // 在函数表达式内部有一个求和的内部函数 var tmp = function(x){ sum = sum + x;// 求和 return tmp; } // 构建一个函数体的toString()函数 tmp.toString = function(){ return sum; } return tmp; // 返回的是一个函数体,如果该函数体有toString()方法,则会调用函数体的toString()方法 }
Then let’s look at the call:
[javascript] view plain copy alert(add(1)(2)(3))
The result is 6. The reason is the same as the first situation we discussed. Next, we call repeatedly:
[javascript] view plain copy // 以下结果输出为:6 alert(add(10)(2)(3)) alert(add(100)(2)(3)) // 下面的结果输出变了 alert(add(1)(3)(3)) alert(add(1)(2)(5))
I believe you have mastered the method after reading these cases. For more exciting information, please pay attention to the php Chinese website Other related articles!
Related reading:
How to make DIV adaptive height
How to use CSS hides the text content of the image background
How to use CSS to hide divs in HTML
The above is the detailed content of Js return value problem. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

To solve the problem that jQuery.val() cannot be used, specific code examples are required. For front-end developers, using jQuery is one of the common operations. Among them, using the .val() method to get or set the value of a form element is a very common operation. However, in some specific cases, the problem of not being able to use the .val() method may arise. This article will introduce some common situations and solutions, and provide specific code examples. Problem Description When using jQuery to develop front-end pages, sometimes you will encounter

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

MySQL is a widely used relational database management system for storing and managing data. When we want to insert new data into a database table, we usually use the INSERT statement. In MySQL, when the INSERT statement is executed to successfully insert data, a result will be returned, which is the result of the insertion operation. In this article, we will discuss in detail the results returned by MySQL after inserting data and provide some specific code examples. 1. The result returned after inserting data is in MySQL. When successfully executed

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
