function factiorial(num) { if (num<=1){ return 1; }else{ return num*arguments.callee(num-1); } } console.log(factiorial(7)); //5040
使用arguments.callee指向正在执行的函数的指针。
function createFunction() { var res =new Array(); for(var i=0;i<10;i++){ res[i] = function () { return i; }(i); } return res; } console.log(createFunction());
虽然知道要执行for循环里面的function,但是闭包还是了解不透彻
var name = "window"; var Obj = { name:"Obj", getName:function () { console.log(this.name); } } Obj.getName(); //Obj
这里没有使用闭包
var name = "window"; var Obj = { name:"Obj", getName:function () { return function () { return console.log(this.name); } } } Obj.getName()(); //window
这里使用了闭包,然后因为函数在被调用时,会产生两个变量,arguments和this。内部函数在搜索这两个变量的时候会搜索到其活动对象为止,而不会访问外部函数的变量。所以返回的是window
var name = "window"; var Obj = { name:"Obj", getName:function () { var _this =this return function () { return console.log(_this.name); } } } Obj.getName()(); //Obj
把外部函数的this保存在一个闭包能访问到的变量里,就可以让闭包访问这个对象。