this

作者: Googler | 来源:发表于2018-07-08 00:01 被阅读1次

    call、apply、函数执行的本质

        "use strict";
    
        function fn(a, b) {
            console.log(this);
        }
    
        fn(1, 2);
        // 等价于
        fn.call(undefined, 1, 2);
        fn.apply(undefined, [1, 2]);
        // 1.在严格模式下,fn里的this就是call的第一个参数,也就是undefined。
        // 2.在非严格模式下,call传递的第一个参数如果是undefined或者null,那this会自动替换为window对象。
    
    
        // 案例一
        var obj = {
            fn1: function (a, b) {
                console.log(this);
            },
            child: {
                fn2: function () {
                    console.log(this);
                }
            }
        }
    
        obj.fn1(1, 2);
        // 等价于
        obj.fn1.call(obj, 1, 2); // this是obj
        obj.fn1.apply(obj, [1, 2]);
    
        obj.child.fn2();
        // 等价于
        obj.child.fn2.call(obj.child); // this是obj.child
    
    
        // 案例二
        var arr = [];
        for (var i = 0; i < 3; i++) {
            arr[i] = function () {
                console.log(this);
            }
        }
    
        var fn = arr[0];
        arr[0](); // this是arr
        fn();  // this是window
    

    bind

        var obj = {
            name: "Googler"
        };
    
        function sayName() {
            console.log(this.name);
        }
    
        // bind的执行结果返回的是绑定了一个对象的新函数
        var fn = sayName.bind(obj); // this是obj
        fn(); // Googler
    

    箭头函数

        let obj = {
            fn1: function (a) {
                console.log(this);
            },
            fn2(a) {
                console.log(this);
            },
            fn3: (a) => {
                console.log(this);
            }
        };
    
        // fn1与fn2完全等价
        obj.fn1(); // obj
        obj.fn2(); // obj
    
        obj.fn3(); // window
    

    结束语

    如果喜欢本文,记得点赞并加关注哟。

    相关文章

      网友评论

        本文标题:this

        本文链接:https://www.haomeiwen.com/subject/yaxnuftx.html