闭包 this 函数对象

77 阅读2分钟

匿名函数

函数的本质就是一个变量
变量--->对象
所以函数是一个对象
因此凡是可以使用对象的地方,都可以使用函数
特殊的两个使用方式:
    1.函数对象作为参数,回调函数
    2.函数对象作为return的返回值(闭包的学习基础)

自运行

自运行针对于,匿名函数
概念:一个函数在定义时,同时被调用,称为自运行
为什么需要自运行,只是闭包写法的先前条件
​
a.用()括起来所有代码  常用这种方法
    (function(){
        console.log("heihei");
    }());
b.用()括起来匿名函数对象
    (function(){
        console.log("haha");
    })();
c.依赖于运算符和关键字
    ! function(){
        console.log("xixixi");
    }();
​
    void function(){
        console.log("hehehe");
    }();

闭包

统计一个函数调用的次数
闭包的概念:函数嵌套函数,被嵌套的函数称为闭包函数
闭包的作用:可以在函数外部使用函数的局部变量
闭包实现的步骤:主函数定义局部变量,嵌套定义子函数,
            子函数中使用父函数的局部变量,主函数将子函数作为返回值,
            在外部通过一个全局变量,绑定主函数的返回值(子函数对象)
            从而将子函数和子函数中使用的局部变量变为全局生命周期
            这样就可以在主函数外界使用局部变量了
闭包的缺陷:打破了垃圾回收机制,延长了局部变量的生命周期,
            可能会造成内存泄露
    function f1(){
        var count = 0;
​
        var f2 = function(){
            ++count;                   
            return count;
        }                
        return f2;
    }
​
    var f = f1();//f == f2
    console.log(f());
    console.log(f());
    console.log(f());
​
-------------------------
优化写法
    function f1(){
        var count = 0;
        return function(){
            return ++count;
        }
    }
​
    var f = f1();
    console.log(f());
    console.log(f());
    console.log(f());
​
完全体
    var f = (function(){
        var count = 0;
        return function(){
            return ++count;
        }
    }());
​
    console.log(f());
    console.log(f());
    console.log(f());

函数对象

函数对象的定义:(只要定义了函数,就会占据空间。)
a.
function fun(){
    console.log("heihei");
}
​
b.
let fun1 = function(){
    console.log("haha");
}
​
c.
 let fun2 = new Function([参数列表],函数体);
 let fun2 = new Function("a","b","console.log(a+b)");
​
 fun2(1,5);

this

函数体内的内置对象
this
1.与事件连用,代表触发事件的元素
    document.onclick = function(){
        console.log(this);
    }
​
2.与普通函数连用(除了事件体,和构造函数),代表调用该函数的对象
    function fun(){
        console.log(this);
    }
    fun();
​
    let json = {
        a:1,
        fun:function(){
            console.log(this);
        }
    }
    json.fun();   
3.与箭头函数连用,代表父元素前缀
    let json = {
        a:1,
        fun:()=>{
            console.log(this);
        }
    }
    json.fun();
4.与构造方法连用,代表new出来的对象本身
    function Student(id){
        this.id = id;
    }