1. Function declaration
function Sum1 (n1,n2) {return
n1+n2;
};
2. Function expression, also known as the literal number of functions
var sum2=function (n1,n2) {return
n1+n2;
};
The difference between the two: the parser reads the function declaration first and makes it accessible before executing any code, and the function expression must wait until the parser executes to the line of code it is in before it is actually interpreted.
The self-execution function is also strictly called a function expression, which is used primarily to create a new scope, a variable declared within the scope that does not conflict with or confuse variables within other scopes, mostly in anonymous functions, and is immediately executed automatically.
(function (n1,n2) {
console.log (n1+n2)
}) (1,3);//4
Several other self-executing functions:
Can be used to pass parameters
(function (x,y) {
console.log (x+y);
}) (2,3);
var sum= with return value
(function (x,y) {returns
x+y;
}) (2,3);
Console.log (sum);
~function () {
var name= ' ~ '
console.log (name);
} ();
! function () {
var name= '! '
) Console.log (name);
();
;( function () {
var name= '; '
Console.log (name);
}) ();
-function () {
var name= '-'
console.log (name);
} ();
Comma operator
1,function () {
var name= ', ';
Console.log (name);
();
XOR or
1^function () {
var name= ' ^ ';
Console.log (name);
();
comparison operator
1>function () {
var name= ' > ';
Console.log (name);
();
~+-! (function () {
var name= ' ~+-! ';
Console.log (name);
}) ();
~! (function () {
var name= ' ~! ';
Console.log (name);
}) ();
(function () {
var name= ' call ';
Console.log (name),
}). Call ();
(function () {
var name= ' Apply ';
Console.log (name),
}). Apply ();
3. The function constructs the method, the parameter must add the quotation mark
var sum3=new Function (' N1 ', ' N2 ', ' return n1+n2 ');
Console.log (sum3 (2,3));//5
From a technical standpoint, this is a function expression. It is not generally recommended to define a function in this way, because this syntax can result in two-time parsing of the code (the first is parsing the regular ECMAScript code, and the second is parsing the string in the incoming constructor), which affects performance.
var name= ' Haoxl ';
function Fun () {
var name= ' Lili ';
return new Function (' return name ');/cannot get local variable
}
Console.log (Fun ());//haoxl
The function () constructor resolves the body of the functions every time it executes and creates a new function object, so it is very inefficient to invoke the function () constructor in a loop or frequently executed function. While the function literal is not recompiled every time it is encountered, creating a function using the function () constructor does not follow the typical scope, which it always treats as a top-level function.