Chapter 9 anonymous functions of Javascript and chapter 9 javascript
Analysis:
1. The so-called anonymous function, literally, is a function without a name. js is replaced by () (Note: it is a bracket in English)
2. Definition form:
function (){ //to add codes that you want to add}
3. Functions of anonymous Functions
(1) Compared with the closure function, GC automatically recycles memory once the global object is executed, which is essentially different from the closure function. A major feature of closure functions is:
Variable resident memory, released only when the browser is closed.
function f1(){ var n=999; nAdd=function(){n+=1} function f2(){ alert(n); } return f2; } var result=f1(); result(); // 999 nAdd(); result(); // 1000
In the code above, the result is actually the f2 function of the closure. It runs twice in total. The first value is 999, and the second value is 1000. This proves that the local variable n in function f1 has been stored in the memory and is not automatically cleared after f1 is called.
Why? The reason is that f1 is the parent function of f2, and f2 is assigned a global variable, which causes f2 to always be in the memory, while f2 depends on f1, therefore, f1 is always in the memory and will not be recycled by the garbage collection mechanism after the call is completed.
Another noteworthy part of this Code is the line "nAdd = function () {n + = 1}". The var keyword is not used before nAdd, therefore, nAdd is a global variable rather than a local variable. Secondly, the value of nAdd is an anonymous function.
The anonymous function itself is also a closure, so nAdd is equivalent to a setter. You can operate on local variables inside the function outside the function.
(2) Compared with general functions, no pre-compilation is performed.
Function fuc () {fuc1 (); // foo is mentioned at the beginning of the scope, so the foo function fuc2 () can be called normally here (); // here the error bar is undefined function fuc1 () {alert ("foo ()")} var fuc2 = function () {alert ("bar ")};}
Code:
Several forms of anonymous functions:
Mode 1: Function Literal)
Declare the function object and then execute it.
(function(){ // insert code here })();
Mode 2: Prior Expression)
Since JavaScript executes expressions in the order from inside to outside, brackets are used to force the execution of declared functions.
(function(){ // insert code here }());
Mode 3: Void Operator)
Use the Void operator to execute a separate operand.
void function(){ // insert code here }();