I encountered some grammatical problems with JS, but I didn’t understand them thoroughly, so I had to make up for the basics!
Anonymous function An anonymous function
An anonymous function without a name is called an “anonymous function”, like this x y}
Without a name, of course it cannot be called directly or called; at most it can only be assigned a value or processed with a closure (what a closure is will be discussed below), such as:
var sum =function(x,y){return x y};
alert(sum(1,2));
At this time, it is equivalent to the traditional writing function sum(x,y ){return x y}. This way of writing makes people feel more OOP, because the sum variable contains the function...this function body;
The function can also be called in a closure way:
(functioin(x,y){return x y})(1,2) //Return value 3
The code is very concise. Note the use of parentheses, in the form (exp)(). This usage can be called closure.
The following brackets are parameters. Put these parameters into fn and calculate them immediately to get a value of 3. This is actually an expression operation. Unexpectedly, the fn function body can also be put in to participate in calculations ^_^ (Using function as an expression)! (Basic skill: Expression, which means that after calculation, a value will always be returned, no matter how long the expression is)
fn can also be passed in the form of parameters (passing function as argument to other functions)
var main_fn = function(fn,x,y){return fn(x,y)}
var sum = function (x,y){
return x y;
}
alert(main_fn(sum,1,2)) // result:3
Summarize (by an IBM Engineer's article, refer to IBM website, it is best to remember it carefully )
Functions need not have names all the time.
Functions can be assigned to variables like other values.
A function expression can be written and enclosed in parenetheses for application later.
Functions can be passed as arguments to oher funcitons.
Let’s talk about closures again. The function of closures is to form a domain. Let’s give a very idiotic example 1 (2 3) , the parenthesis part takes precedence, or to put it another way, what is inside the parentheses is classified into a range. I don’t care what you do in this range, it’s all what you do inside, and has nothing to do with the outside world of the parentheses (it seems to be nonsense, - that’s what I think) , that’s how it’s written @#@), and the same is true for program understanding. JS has a function scope, so when there is a problem using this to point to an object, you can consider using a closure. Specific examples are at: http://www.svendtofte.com/code/practical_functional_js/