This example describes the use of JavaScript anonymous functions. Share to everyone for your reference. Specifically as follows:
One, define a function
In JavaScript, you can define a function by "function declaration" and "function expression", such as
1, through "function declaration" to define a function
2, through "function expression" to define a function
But two ways to define a function, the effect is different
T1 is a function declaration, ' lexical parsing ', ao.t1 = function () {},-------------play a role in the ' lexical analysis ' phase
T2 is an assignment operation, ' run ', ao.t2 = function () {}, the value is the result of the expression returned on the right,------play a role in the ' run ' phase
Second, anonymous function
In JavaScript, the statements in parentheses () are executed as expressions, and as mentioned above, you can define a function by using a function expression, so we can define a function in (), such as
(function t3 () {alert (' I am T3 ');})
If the function does not use a name, modify the following
(function () {alert (' I am T3 ');})
The statement contained within () has a return value since it is an expression (function () {alert (' I am T3 ');}) The return value is a defined function that can be called immediately, as
(function () {alert (' I am T3 ');}) ()
Therefore, within the parentheses (), a function without a name is defined, which is called an anonymous function. This technique, the anonymous function, executes immediately, does not pollute the global, and is called an immediate execution function expression.
Three, jquery is an anonymous function
The jquery code is encapsulated in an anonymous function, which is the outermost code of jquery:
(function (window,undefined) {}) (window);/Call immediately
But why does jquery pass windows, not undefined?
Answer: The window is to find the speed, reduce the time to query variables. Like the following JS code
function () {function () {function () {function () {
document.getElementById ();
This document will be found along the scope layer until the outermost window is global.
}
}
}
}
In order to speed up the internal lookup of local variables, jquery directly passes the window as a parameter, so that Windows is inside the jquery ao.
Undefined is for security, because in the lower version of the ie,ff, undefined can be assigned a value, such as undefined=3;
Declare local variable undefined (name is undefined), at the same time, do not pass the parameter, the value is naturally undefined
I hope this article will help you with your JavaScript programming.