


Understanding javascript anonymous functions (thorough version)_javascript skills
(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:
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:
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:
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:
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:
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.
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:
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?

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

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

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











An anonymous function, also known as a lambda expression, is a function that does not specify a name and is used for one-time use or to pass a function pointer. Features include: anonymity, one-time use, closures, return type inference. In practice, it is often used for sorting or other one-time function calls.

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

Yes, anonymous functions in Go language can return multiple values. Syntax: func(arg1,arg2,...,argN)(ret1,ret2,...,retM){//Function body}. Usage: Use the := operator to receive the return value; use the return keyword to return multiple values.

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

A python Lambda expression is a small anonymous function that stores an expression in a variable and returns its value. Lambda expressions are often used to perform simple tasks that can be accomplished by writing a separate function, but Lambda expressions can make the code more concise and readable. The syntax of a Lambda expression is as follows: lambdaarguments: expressionarguments is the parameter list received by the Lambda expression, and expression is the body of the Lambda expression, which contains the code that needs to be executed. For example, the following Lambda expression adds two numbers and returns their sum: lambdax,

Lambda expressions and anonymous functions are both ways of creating anonymous functions in Python, but there are differences. Assignment method: lambda expression returns a function, and anonymous functions must be assigned to variables to be used. Code complexity: A lambda expression can only contain one expression, while an anonymous function can contain multiple statements.

pythonLambda expressions are a powerful and flexible tool for creating concise, readable, and easy-to-use code. They are great for quickly creating anonymous functions that can be passed as arguments to other functions or stored in variables. The basic syntax of a Lambda expression is as follows: lambdaarguments:expression For example, the following Lambda expression adds two numbers: lambdax,y:x+y This Lambda expression can be passed to another function as an argument as follows: defsum( x,y):returnx+yresult=sum(lambdax,y:x+y,1,2)In this example
