SoFunction
Updated on 2025-04-13

Study the second day

I encountered some JS syntax problems and did not understand them thoroughly, so I would make up for the basic skills!

 

An anonymous function

If you don't have a name, it's called "anonymous function", like this

function(x,y){return x+y}

Of course, you cannot call directly without a name, nor can you call it; at most you can only assign it to a value or process the closure (what is a closure is 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 method function sum(x,y){return x+y}. This writing method makes people feel more OOP, because the sum variable contains function... this function body;

You can also call this function in a closure:

(function(x,y){return x+y})(1,2) //Return value 3

The code is very concise. Pay attention to the use of brackets, the form is (exp)(). This usage can be called closure.
The following brackets are the parameters. Put these parameters into fn and calculate them immediately to obtain a value of 3. This is actually an operation of an expression. I didn’t expect that the fn function body can also be put in to participate in the operation^_^(Using function as an expression)! (Basic skill: Expression, whose meaning is that after calculation, a value will always be returned, no matter how long the expression is)

fn can also be passed in parameter form (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

To sum up (by an IBM Engineer's article, refer to IBM website, it’s 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. The function of closures is to form a definition domain. Take a very idiotic example. 1+(2+3), the brackets are preferred for operation, or to put it another way, the brackets are classified as a range. I ignore this range. Whatever you do is what you do, and has nothing to do with the outside world of brackets (it seems to be nonsense, -- I think so, I wrote this @#@), and the same is true for the program. js has a function domain function scope, so when there is a problem with pointing to an object using this, you can consider using closures. Specific examples are: /code/practical_functional_js/