Common Methods for defining functions:
A feature of function declaration: Improvement of function declaration;
Function declaration:
function fName(){}
Function expressions are also common methods for creating functions:
var fName = function ( ) { }
函数表达式的另一种声明的方法:
(function f(){}); //()是一组分组操作符,它的内部只能包含表达式
Note: function expressions, like other expressions, must be assigned before use. You can use anonymous functions when using functions as values,
But this is not the only use of anonymous functions.
You can also create a function and return a function in another function.
function create ( ){ .......... return function( ){ ........ }; }
Function Recursion: When a function calls itself
funtion fName (){ if(num <= 1){ return 1; }else{ return num * arguments.callee( num -1 );//arguments.callee是一个指向当前函数的一个指针 }}
Closure: Refers to the function that has the right to access the variables in another function scope. The closure will carry the scope variable object of the function that contains it.
Example of a closure:
1 var name = " 闭包"; 2 3 var object = { 4 5 name : "JS", 6 7 getName : function(){ 8 9 //这是一个闭包10 return function(){11 return this.name;12 };13 14 }15 16 };
In the above example, we talk about the this object of the closure. The this object of the closure usually points to the window;
1 var name = " 闭包"; 2 3 var object = { 4 5 name : "JS", 6 7 getName : function(){ 8 9 //这是一个闭包10 return function(){11 return this.name;12 };13 14 }15 16 };17 18 console.log(object.getName()()); //输出闭包 this指向 window
1 var name = " 闭包"; 2 3 var object = { 4 5 name : "JS", 6 7 getName : function(){ 8 9 //把包含函数的this引用复制给变量,在闭包中调用,改变闭包的this引用10 11 var _this = this;12 13 //这是一个闭包14 return function(){15 return _this.name;16 };17 18 }19 20 };21 22 console.log(object.getName()()); //输出JS this指向 object
Function Description and function expression