In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
What is the function of Javascript anonymous function and self-executing function? I believe many inexperienced people are at a loss about this. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Functions are one of the most flexible objects in JavaScript, and I'm just here to explain the purpose of their anonymous functions. Anonymous functions: functions that do not have a function name.
The definition of function can be roughly divided into three ways:
The first one: this is also the most conventional one.
?
one
two
three
Function double (x) {
Return 2 * x
}
Second: this method uses the Function constructor, the parameter list and function body as strings, which is very inconvenient and is not recommended.
?
one
Var double = new Function ('x, 'return 2 * x * *)
The third kind:
?
one
Var double = function (x) {return 2x;}
Notice that the function to the right of "=" is an anonymous function, and after the function is created, it is assigned to the variable square.
Creation of anonymous functions
The first way is to define the square function mentioned above, which is also one of the most commonly used ways.
The second way:
?
one
two
three
(function (x, y) {
Alert (x + y)
}) (2,3)
An anonymous function is created (in the first parenthesis), and the second parenthesis is used to call the anonymous function, passing in parameters. Parentheses are expressions, and expressions have a return value, so you can add a pair of parentheses to let them execute.
Self-executing anonymous function
1. What is a self-executing anonymous function?
It refers to a function like this: (function {/ / code}) ()
two。 Doubt
Why (function {/ / code}) (); can be executed, but function {/ / code} (); will report an error?
3. Analysis.
(1)。 First of all, make clear the difference between the two:
(function {/ / code}) is an expression, and function {/ / code} is a function declaration.
(2)。 Secondly, the characteristics of js "pre-compilation":
During the precompilation phase, js interprets function declarations, but ignores expressions.
(3)。 When js executes to function () {/ / code} ();, since function () {/ / code} has been explained in the "precompilation" phase, js will skip function () {/ / code} and try to execute ();, so an error will be reported.
When js executes to (function {/ / code}) ();, because (function {/ / code}) is an expression, js will evaluate it to get the return value, and because the return value is a function, it will be executed.
In addition, the method of converting a function to an expression does not have to rely on the grouping operator (), we can also use the void operator, ~ operator,! Operator...
Such as:
?
one
two
three
! function () {
Alert ("alternative anonymous function self-execution")
} ()
Anonymous functions and closures
The English word of closure is closure, which is a very important part of JavaScript knowledge, because using closures can greatly reduce the amount of our code, make our code look clearer, etc., in short, the function is very powerful.
The meaning of the closure: the closure is simply the nesting of functions, and the inner function can use all the variables of the outer function, even if the outer function has been executed (this involves the JavaScript scope chain).
?
one
two
three
four
five
six
seven
Function checkClosure () {
Var str = 'rain-man'
SetTimeout (
Function () {alert (str);} / / this is an anonymous function
, 2000)
}
CheckClosure ()
This example looks very simple, and there are still many knowledge points after a careful analysis of its execution process: the execution of the checkClosure function is instantaneous (perhaps only 0.00001 milliseconds), a variable str is created in the body of the checkClosure function, and str is not released after the checkClosure execution is completed, this is because the anonymous function in setTimeout has this reference to str. Str is not released until 2 seconds later when the anonymous function inside the function is executed.
Optimize the code with closures:
?
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
Function forTimeout (x, y) {
Alert (x + y)
}
Function delay (x, y, time) {
SetTimeout ('forTimeout (' + x +','+ y +')', time)
}
/ * *
* the delay function above is very difficult to read and not easy to write, but you can make the code clearer if you use closures
* function delay (x, y, time) {
* setTimeout (
* function () {
* forTimeout (x, y)
*}
*, time)
*}
, /
The greatest use of anonymous functions is to create closures (which is a feature of the JavaScript language) and to build namespaces to reduce the use of global variables.
?
one
two
three
four
five
six
seven
eight
Var oEvent = {}
(function () {
Var addEvent = function () {/ * the implementation of the code omits * /}
Function removeEvent () {}
OEvent.addEvent = addEvent
OEvent.removeEvent = removeEvent
) ()
In this code, the functions addEvent and removeEvent are local variables, but we can use it through the global variable oEvent, which greatly reduces the use of global variables and enhances the security of the web page.
To use this code:
?
one
two
three
four
five
six
seven
eight
nine
OEvent.addEvent (document.getElementById ('box'),' click', function () {})
Var rainman = (function (x, y) {
Return x + y
}) (2,3)
/ * *
* it can also be written in the following form, because the first parenthesis is only to help us read, but the following writing format is not recommended.
* var rainman = function (x, y) {
* return x + y
*} (2, 3)
Here we create a variable rainman and initialize it to 5 by calling the anonymous function directly, which is sometimes very useful.
?
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
Var outer = null
(function () {
Var one = 1
Function inner () {
One + = 1
Alert (one)
}
Outer = inner
) ()
Outer (); / / 2
Outer (); / / 3
Outer (); / / 4
The variable one in this code is a local variable (because it is defined within a function), so it is not externally accessible. But here we create the inner function, which accesses the variable one, and references the global variable outer to inner, so calling outer three times will pop up an incremental result.
Be careful
The 1 closure allows the inner function to refer to a variable in the parent function, but the variable is the final value
?
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
/ * *
*
*
* one
* two
* three
* one
*
, /
Var lists = document.getElementsByTagName ('li')
For (var I = 0, len = lists.length; I < len; iTunes +) {
Lists [I] .onmouseover = function () {
Alert (I)
}
}
You will find that when the mouse moves over each element, it always pops up 4, not the element subscript we expect. Why is that? It has been mentioned in the notes (final value). Obviously, this explanation is too simple. When the mouseover event calls the listener function, it first looks inside the anonymous function (function () {alert (I);}) to see if I is defined, and the result is undefined; so it looks up, and the result is defined, and the value of I is 4 (the I value after the loop); so, in the end, it pops up with 4.
Solution 1:
?
one
two
three
four
five
six
seven
eight
Var lists = document.getElementsByTagName ('li')
For (var I = 0, len = lists.length; I < len; iTunes +) {
(function (index) {
Lists [index] .onmouseover = function () {
Alert (index)
}
}) (I)
}
Solution 2:
?
one
two
three
four
five
six
seven
Var lists = document.getElementsByTagName ('li')
For (var I = 0, len = lists.length; I < len; iTunes +) {
Lists [I]. $$index = I; / / record the subscript by binding the $$index attribute to the Dom element
Lists [I] .onmouseover = function () {
Alert (this.$$index)
}
}
Solution 3:
?
one
two
three
four
five
six
seven
eight
nine
Function eventListener (list, index) {
List.onmouseover = function () {
Alert (index)
}
}
Var lists = document.getElementsByTagName ('li')
For (var I = 0, len = lists.length; I < len; iTunes +) {
EventListener (lists [I], I)
}
2 memory leak
Using closures can easily cause memory leaks in browsers, and in serious cases, browsers will hang up.
After reading the above, have you mastered the method of Javascript anonymous function and self-executing function? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.