JavaScript anonymous function Usage Analysis, javascript anonymous Function
This example describes how to use JavaScript anonymous functions. Share it with you for your reference. The details are as follows:
1. Define a function
In JavaScript, you can use "function declaration" and "function expression" to define a function, such
1. Define a function through "function declaration"
function t1(){}
2. Define a function through a "function expression"
t2 = function(){}
However, the two methods define functions with different effects.
T1 is a function declaration. When 'lexical analytics 'is used, AO. t1 = function () {}, ----------- plays a role in the 'lexical analytics' stage.
T2 is a value assignment operation. When 'run' is run, AO. t2 = function () {}, and the value is the result returned by the expression on the right. ------ plays a role in the 'run' stage.
Ii. Anonymous Functions
In JavaScript, the statements in parentheses () are executed as expressions. As mentioned above, we can use "function expressions" to define a function. Then, we can () define a function, such
(function t3(){alert(' i am t3');})
If this function does not use a name, modify it as follows:
(function(){alert(' i am t3');})
Since the statement contained in () is an expression, there is a return value. (function () {alert ('I am t3') ;}) the return value is the defined function, can be called immediately, as shown in figure
(function(){alert(' i am t3');})()
Therefore, a function without a name is defined in parentheses (). This function is called an anonymous function. In this way, an anonymous function is executed immediately without affecting the whole world. It is called an immediate execution function expression.
Iii. jquery is an anonymous Function
Jquery code is encapsulated in an anonymous function, which is the code of the outermost layer of jquery:
(Function (window, undefined) {}) (window); // call now
But why does jquery pass the window without undefined?
A: The window is used to query the speed and reduce the time for querying variables. For example, the following JavaScript code
Function () {document. getElementById (); // This document will be searched along the scope layer until the window on the outermost layer is global. }}}}
Jquery directly transmits the window as a parameter to speed up local variable search, so that the window is on the internal AO of jquery.
Undefined is not passed for security, because in earlier versions of IE and FF, undefined can be re-assigned, for example, undefined = 3;
Declare the local variable undefined (the name is undefined) without passing the parameter. The value is naturally undefined.
I hope this article will help you design javascript programs.