The recent understanding of JavaScript has given me a different feeling. There’s a lot of resonance! This time I heard some insights about different types of functions to share with you
The following example is a function named box, with no parameters, returning Lee, and alert is the output function
function box (){ return 'lee'; } alert(box());
The following example is an anonymous function. The difference from an ordinary function is that it has no name, so when we only write an anonymous function, it cannot be executed because it has no name. , cannot use alert
//匿名函数 ,不可以运行function (){ return 'lee'; }
because we have an anonymous function Unable to run, so we assign the anonymous function to a variable and run our anonymous function indirectly through the variable
//匿名函数付给变量 var box =function (){ return 'leee'; } alert(box());
//通过自我执行(function (){ (函数)() alert('lee'); })()
//自我执行后用alert打印alert((function(){ return'leee'; })());
//自我执行传参(function(age){ alert(age); })(100)
Closure means to put a function inside the function and then display
//函数里面放一个函数=====和上一个是一样的function box(){ return function (){ //闭包 return 'lee'; } } var b=box(); alert(b());
The local variables of the function cannot be accumulated because it uses global variables. Global variables cannot be saved in memory, but closures can accumulate, and closures can accumulate local variables. Local variables can be saved in memory, so they can be accumulated, but local variables can be used frequently because they occupy too much memory.
//通过使用闭包实现局部累加 function box(){ var age=100; return function(){ age++; return age; }; } var boxx=box(); alert(boxx()); alert(boxx()); boxx=null; //表示解除引用
Study seriously! Don’t ask for progress! Seeking the best! Everything is knowledge, it depends on whether you want to learn it or not!
The above is the detailed content of Different kinds of functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!