search
HomeWeb Front-endJS TutorialUnderstanding javascript anonymous functions (thorough version)_javascript skills

Copy code The code is as follows:

(function(){
//Ignore all jQuery implementations here
})();
(function(){ //Ignore all implementations of jQuery here})();

When I first came into contact with jQuery half a year ago, I was like other people I am also very excited to see what the source code looks like. However, the first time I saw the source code, I was confused. Why can there be a function library like jQuery when there is only one anonymous function and no one sees it running (of course it is running...)? So, I came to CSDN with questions. As a result, I believe many people are very clear about it now (because there are many others coming after me, haha~). When an anonymous function is enclosed in parentheses and then followed by parentheses, the anonymous function can be run immediately! How amazing!

Hehe! So much for the nonsense. In this section, the jQuery snippet we encountered is a set of anonymous functions that run immediately. This usage has also caused heated debates on forums - does this code belong to a closure? With this question in mind, we start from the basics, analyze each key element, and find our own answer. (Yes, my own answer! In my opinion, all theories are just forms. As long as it is conducive to the implementation of our applications, it is desirable - black cats and white cats, the one that catches mice is a good cat!)

To talk about anonymous functions, we must first start with the function itself. The definition of a function is as follows:

A function is a "rule" that assigns a unique output value to each input.

Of course, this is just a mathematical definition. However, in computer programming languages, the definition of functions is similar. Because we all know that a function in a computer is similar to the description in the mathematical definition. It is a set of code combination blocks that process some input data through logical operations set by the code and return a unique output. ——Of course, the special case is that the input data is empty or the output data is empty, or both are empty.

Next, let’s take a preliminary look at the concepts related to anonymous functions.

Function declaration (function statement)
To use a function, we must first declare its existence. The most common way we use function statements is to define a function, such as:

Copy code The code is as follows:

function abc(){
// code to process
}
function abc(){ // code to process }
 Of course, your function can also be With parameters, even with return values.

view plaincopy to clipboardprint?
function abc(x,y){
return x y;
}
function abc(x,y){ return x y; }

However, no matter how you define your function, the JS interpreter will translate it into a Function object. For example, if you are defining the function number in one of the examples above, and then enter the following code:

alert(typeof abc);// "function"
Your browser will pop up a prompt box, prompting Your abc is a Function object. So what exactly is a Function object?

Function object
Function object is an inherent object in JavaScript. All functions are actually a Function object. We leave the discussion of this aspect to the next topic section. Let's first see if the Function object can directly use the constructor to create a new function? The answer is yes. For example:

Copy code The code is as follows:

var abc = new Function(" x","y","return x*y;");
alert(abc(2,3)); // "6"
var abc = new Function("x","y" ,"return x*y;"); alert(abc(2,3)); // "6"

I believe you now have an understanding of how to declare a function. So what is an anonymous function?

Declare anonymous functions
As the name suggests, anonymous functions are functions without actual names. For example, let’s remove the name of the function in the above example and then determine whether it is a function:

Copy code The code is as follows:

alert(typeof function(){});// "function"
alert(typeof function(x,y){return x y;});// "function"
alert(typeof new Function("x","y","return x*y;"))// "function"
alert(typeof function(){});// " function" alert(typeof function(x,y){return x y;});// "function" alert(typeof new Function("x","y","return x*y;"))// "function "

We can easily see that they are all Function objects, in other words, they are all functions, but they all have one feature - no name. So we call them "anonymous functions". However, just because they don’t have “names,” we have no way of finding them. This leads to the question of how to call an anonymous function.

Call of anonymous function
To call a function, we must have a way to locate it and reference it. So, we'll need to find a name for it. For example:
Copy code The code is as follows:

var abc=function(x,y){
return x y;
}
alert(abc(2,3)); // "5"
var abc=function(x,y){ return x y; } alert(abc(2 ,3)); // "5"

The above operation is actually equivalent to defining the function in another way. This usage is something we encounter more frequently. For example, when we set a DOM element event handling function, we usually do not give them a name, but give its corresponding event reference an anonymous function.

There is actually another way to call anonymous functions, which is the jQuery fragment we saw - using () to enclose the anonymous function, and then add a pair of parentheses (including the parameter list). Let’s take a look at the following example again:

Copy the code The code is as follows:

alert( (function(x,y){return x y;})(2,3));// "5"
alert((new Function("x","y","return x*y;") )(2,3));// "6"
alert((function(x,y){return x y;})(2,3));// "5" alert((new Function(" x","y","return x*y;"))(2,3));// "6"

Many people may wonder why this method can be called successfully Woolen cloth? For those who think this application is strange, please read my explanation below.

Do you know the function of parentheses? Parentheses can divide our expression combination into blocks, and each block, that is, each pair of parentheses, has a return value. This return value is actually the return value of the expression in parentheses. Therefore, when we use a pair of parentheses to surround an anonymous function, what the pair of parentheses actually returns is a Function object of the anonymous function. Therefore, a pair of parentheses plus an anonymous function is referenced by us just like a named function. So if you add a parameter list after this reference variable, the calling form of an ordinary function will be achieved.

I don’t know if you can understand the above textual expression. If you still can’t understand it, try looking at the following code.
Copy code The code is as follows:

var abc=function(x,y){return x y ;};// Assign the anonymous function object to abc
// The constructor of abc is the same as the constructor of the anonymous function. In other words, the implementation of the two functions is the same.
alert((abc).constructor==(function(x,y){return x y;}).constructor);
var abc=function(x,y){return x y;};// The anonymous function object is assigned to abc // The constructor of abc is the same as the constructor of the anonymous function. In other words, the implementation of the two functions is the same. alert((abc).constructor==(function(x,y){return x y;}).constructor);

PS: Constructor refers to the function that creates objects. That is, the function body represented by the function object.

In short, understand it (the anonymous function enclosed by parentheses) as the function object returned by the parentheses expression, and then you can make a normal parameter list call to this function object. (I made a mistake here before. You cannot directly call a function with only a function expression. Removing the anonymous function brackets must be accompanied by assigning the expression. That is, (function(){alert(1)})() should be the same as a =function(){alert(1)}() is equivalent, you cannot remove a=. )

Closure
 What is a closure? Closure refers to a code block in a certain programming language that allows a first-level function to exist and the free variables defined in the first-level function cannot be released. Until the first-level function is released, these unused variables can also be applied outside the first-level function. Free variables released.

How? You must be sweating after watching it... It's okay, me too (although I understand it, it's just a matter of my ability to express myself). Let's explain it in a simpler way: closure is actually a language feature. It refers to a programming language that allows functions to be treated as objects, and then operations like operations in the object can be moved to define instances in the function. (local) variables, and these variables can be saved in the function until the instance object of the function is destroyed. Other code blocks can obtain the values ​​​​of these instance (local) variables in some way and extend the application.

I don’t know if it will be clearer after explaining it this way. If you still don’t understand, let’s simplify it again: closure actually refers to a local part defined in a programming language that allows code to call a running function. variable.

Now let’s look at an example:
Copy the code The code is as follows:

var abc=function(y){
var x=y;// This is a local variable
return function(){
alert(x );// This is where one of the closure features is called Level function local variable // "5" "5"
abc();// "6" "4"
abc();// "7" "3"
alert(x);// Error! "x" is not defined!
var abc=function(y){ var x=y;// This is the local variable return function(){ alert(x);// This is where the x of the first-level function local variable in the closure feature is called , and operate on it alert(y--);//The referenced parameter variable is also a free variable}}(5);//Initialize abc();// "5" "5" abc();// " 6" "4" abc();// "7" "3" alert(x);// Error! "x" is not defined!


Seeing this, can you tell whether the jQuery code snippet is closed?
Let’s use my understanding. Whether the closure feature is applied, you must determine whether the code has the most important element: local variables that have not been destroyed. Then it is obvious that an anonymous function without any implementation cannot apply the closure feature. But what if there is an implementation in the anonymous function? Then you have to make sure whether any local variables that have not been destroyed are used in its implementation. So if I ask you what features of JS are used in the jQuery code snippet in the opening article? Then it's just anonymous functions and anonymous function calls. However, it implies the properties of closures, and closures can be applied at any time. Because JS is born with this feature! (This is just my understanding. I also want to know your understanding. Welcome to communicate! Regarding closures, if you have the opportunity, let’s open another topic independently!)
Statement
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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 Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool