函数中的this指向

函数中的this指向与函数的调用形式有关

函数调用

普通函数调用

函数调用形式下,this永远这都是指向window

我们用一个例子来证明一下
        function fn() {
    
    
            console.log(this); // Window
            function foo() {
    
    
                console.log(this); // Window
            }
            foo()
        }
        fn()
        
        // fn在全局下调用指向window
        // 而foo在函数fn里面调用,也指向window

构造函数调用

        function Person(name) {
    
    
            this.name = name
            console.log(this.name); // zs
        }
        
        const obj = new Person('zs');
        
        // 函数作为构造函数时

        // new关键字发挥其作用
        // 首先创建了一个新的对象
        // 然后让this指向该对象
        // 并且让对象的__proto__ 指向函数的prototype
        // 执行函数里的里的代码
        // 最后返回这个新的实例对象

        // 所以函数作为构造函数时,里面的this会指向创建的实例对象
        // this指向构造出来的实例对象

方法调用

当函数作为对象的方法,进行调用时,this会指向这个对象

        const obj = new Person('zs');
        obj.set = function () {
    
    
            console.log(this); // obj
        }
        obj.set()
事件函数也是一样,会指向触发该事件所绑定的对象

        document.querySelector('button').onclick = function () {
    
    
            console.log(this);
        }
        // this指向获取绑定该点击事件的节点对象

ES6中的箭头函数 this指向

准确来讲,箭头函数并没有 this , 要在箭头函数里使用 this ,那么它会指向该箭头函数在定义时的外层函数中的 this 。

        const fn1 = () => {
    
    
            console.log(this); // window
        }
        fn1()
        // 这时候fn1中的this会指向window
        function fn() {
    
    
            let that = this
            console.log(this); // window
            const fn2 = () => {
    
    
                console.log(this); // window
                console.log(this === that); // true
            }
            fn2()
            // 这时fn2中的this会指向fn中的this,也就是window
        }
        fn()

        const obj = {
    
    
            set: function () {
    
    
                let that = this
                console.log(this); // obj
                const fn3 = () => {
    
    
                    console.log(this); // obj
                    console.log(this === that); // true
                }
                fn3()
                // 这时fn2中的this会指向fn中的this,也就是obj
            }
        }
        obj.set()

         function foo1() {
    
    
             console.log(this);
         }
         document.querySelector('button').onclick = foo1
         // this指向获取绑定该点击事件的节点对象


        const foo2 = () => {
    
    
            console.log(this);
        }
        document.querySelector('button').onclick = foo2
        // this依然指向 window	没有被改变

call 与 apply

call 与 apply 可以改变函数中this的指向

        const obj = {
    
    
            name: 'zs'
        }
        const set = function () {
    
    
            console.log(this);
        }

        set.call(obj);  // obj

        set.apply(obj);  // obj

猜你喜欢

转载自blog.csdn.net/m0_37825174/article/details/115023650
今日推荐