SoFunction
Updated on 2025-03-03

Analysis of the usage of anonymous functions in JavaScript

This article describes the usage of JavaScript anonymous functions. Share it for your reference. The details are as follows:

1. Define a function

In JavaScript, a function can be defined through "function declaration" and "function expression", for example

1. Define a function through "function declaration"

function t1(){}

2. Define a function through "function expression"

t2 = function(){}

However, the two ways to define functions have different effects
t1 is a function declaration. When 'lexical analysis', AO.t1 = function(){},---------------------------------------------------------------------------------------------------
t2 is an assignment operation. When ‘run’, AO.t2 = function(){}, the value is the result returned by the expression on the right, and it only works in the ‘run’ stage

2. Anonymous functions

In JavaScript, the statement in brackets() is executed as an expression. As mentioned above, you can use "function expression" to define a function, so we can define a function in (), such as

(function t3(){alert(' i am t3');})

If the function does not use the name, modify it as follows

(function(){alert(' i am t3');})

Since the statement contained in() is an expression, it has a return value. The return value of (function(){alert(' i am t3');}) is a defined function and can be called immediately, such as

(function(){alert(' i am t3');})()

Therefore, a function without a name is defined in brackets(), which is called anonymous function. This method, anonymous functions, execute immediately without polluting the global situation, is called executing function expressions immediately.

3. jquery is an anonymous function

The code of jquery is encapsulated in an anonymous function, which is the outermost code of jquery:

(function(window,undefined){})(window);//Call now

But why does jquery pass the window but not undefined?

Answer: Passing window is to find speed and reduce the time to query variables. For example, the following js code

function(){
 function(){
   function(){
  function(){
   ();
//This document will be searched layer by layer along the scope until the outermost window globally.  }
   }
 }
}

jquery is to speed up the internal search of local variables, and directly pass the window in as parameters, so that the window is on the AO inside jquery.

It is for security purposes not to pass undefined, because in the lower versions of IE and FF, undefined can actually be reassigned, such as undefined=3;

Declare the local variable undefined (name is undefined), and at the same time, without passing the parameters, the value is naturally undefined

I hope this article will be helpful to everyone's JavaScript programming.