Home > Article > Web Front-end > JavaScript function expressions (graphic tutorial)
This article mainly introduces the detailed explanation and examples of JavaScript function expressions. Friends who need it can refer to
JavaScript function expressions
1. Preface
There are two ways to define a function: one is a function declaration, and the other is a function expression;
1.1 Function declaration
function functionName(arg){ //函数体 }
Regarding function declaration, one of its important features is function declaration promotion, which means that the function declaration will be read before executing the code. This means that the function can be placed after the statement that calls it. As shown below:
helloworld(); //在代码执行之前会先读取函数声明 function helloworld(){ console.log("hello world"); }
1.2 Function expression
var functionName=function(arg){ //函数体 }
This form looks like It looks like a regular variable assignment statement, that is, creating a function and assigning it to the variable functionName. The function created in this case is called an anonymous function. Because there is no identifier after the function keyword.
Function expressions, like other expressions, must be assigned a value before use; the following code will cause an error;
helloworld(); //错误,还未赋值,函数不存在 var helloworld=function(){ console.log("hello world"); }
There With the function expression, we can dynamically assign values to the function expression; as shown in the following code:
var helloworld; //声明 if(condition){ //条件 helloworld=function(){ //赋值 console.log("hello world"); } } else{ helloworld=function(){ //赋值 console.log("你好,世界"); } }
2. Recursive function
A recursive function is formed when a function calls itself by name (the same as C# and other languages, so the core idea of the program is similar, except for some differences in syntax. Learn the basics of a language well and learn Others will be much easier). Take a classic recursion interview question. The rules for a column of numbers are as follows: 1, 1, 2, 3, 5, 8, 13, 21, 34... To find the 30th digit, use recursion Algorithm implementation, the code is as follows:
function foo(n) { if (n <= 0) return 0; else if (n > 0 && n <= 2) return 1; else return foo(n - 1) + foo(n - 2); }
Although this function seems to have no problem, the following code may cause it to go wrong:
var foo1 = foo; foo = null; console.log(foo1(34));
The above code first saves the foo() function in the variable foo1, and then sets the foo variable to null. As a result, there is only one reference to the original function. But when foo1() is called next, since foo() must be executed and foo is already null, an error will occur; in this case, using arguments.callee can solve this problem. arguments.callee is a pointer to the function being executed, so you can use it to implement recursive calls to the function
function foo(n) { if (n <= 0) return 0; else if (n > 0 && n <= 2) return 1; else return arguments.callee(n - 1) + arguments.callee(n - 2); }
You can also use named function expressions to achieve the same result. For example:
var foo = (function f(n) { if (n <= 0) return 0; else if (n > 0 && n <= 2) return 1; else return f(n - 1) + f(n - 2); });
3. Closure
3.1 Closure means the right to access another function scope A common way to create a closure is to create a function inside a function. To understand closures, you must first understand the scope of JavaScript special variables. The scope of variables is nothing more than two types, global variables and local variables; Next, write a few demos to express it intuitively;
Read global variables directly inside the function:
var n = 100; //定义一个全局变量 function fn() { console.log(n); //函数内部直接读取全局变量 } fn();
Local variables cannot be read directly outside the function:
function fn() { var n = 100; } console.log(n); //n is not defined
There is something to note here, which is to declare it inside the function When using variables, be sure to use var. If it is not used, it will become a global variable:
function fn() { n = 100; } fn(); console.log(n); //100
Sometimes we need to get the variables declared inside the function, So you can use the common way of creating closures mentioned above to create another function inside the function:
function fn() { n = 100; function fn1() { console.log(n); } fn1(); } fn(); //100
In the above code, function fn1 is Included inside function fn, all local variables inside fm are visible to fn1. But the reverse doesn't work. The local variables inside fn1 are invisible to fn. This is the unique "chain scope" structure of the Javascript language. The child object will look up the variables of all parent objects level by level. Therefore, all variables of the parent object are visible to the child object, but not vice versa.
It turns out that fn1 can read the internal variables of fn, so as long as fn1 is used as the return value, we can read the variables of fn externally
function fn() { n = 100; function fn1() { console.log(n); } return fn1; } var result=fn(); result(); //100
Here fn1 is a closure, and a closure is a function that can read the internal variables of other functions. Since in the Javascript language, only subfunctions within the function can read local variables, closures can be simply understood as "functions defined inside a function". So, in essence, closure is a bridge connecting the inside of the function with the outside of the function.
3.2 The purpose of closure
It has two biggest uses. One is to read the variables inside the function as mentioned earlier, and the other is to keep the values of these variables at all times. in memory. As shown in the following code:
function fn() { n = 100; nadd = function () { n += 1; } function fn1() { console.log(n); } return fn1; } var result = fn(); result(); //100 nadd(); result(); //101
注意:由于闭包函数会携带包含它的函数的作用域,因此会比其他函数占用更多的内存,过度使用闭包可能会导致内存占用过多,所以在退出函数之前,将不使用的局部变量全部删除。
四、块级作用域
块级作用域(又称为私有作用域)的匿名函数的语法如下所示:
(function(){ //块级作用域 })();
无论在什么地方,只要临时需要一些变量,就可以使用私有作用域,比如:
(function () { var now = new Date(); if (now.getMonth() == 0 && now.getDate() == 1) { alert("新年快乐"); } })();
把上面这段代码放到全局作用域中,如果到了1月1日就会弹出“新年快乐”的祝福;这种技术经常在全局作用域中被用在函数外部,从而限制向全局作用域中添加过多的变量和函数。一般来说,我们都应该尽量少向全局作用域中添加变量和函数。在一个由很多开发人员共同参与的大型应用程序中,过多的全局变量和函数很容易导致命名冲突。而通过创建私用作用域,每个开发人员既可以使用自己的变量,又不必担心搞乱全局作用域。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of JavaScript function expressions (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!