zoukankan      html  css  js  c++  java
  • 递归 闭包

    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保存在一个闭包能访问到的变量里,就可以让闭包访问这个对象。

  • 相关阅读:
    vue中height设置为100%却无法铺满整个页面
    cpp快速上手
    CSP_2020061_线性分类器
    cpp快速上手
    算法笔记
    cpp中set的使用
    cpp中vector的使用
    常用命令
    常用git命令
    Linux使用docker安装fastfs
  • 原文地址:https://www.cnblogs.com/vivenZ/p/6435702.html
Copyright © 2011-2022 走看看