JavaScript - this指向的总结

106 阅读2分钟

这是我参与2022首次更文挑战的第4天,活动详情查看:2022首次更文挑战

image.png

  • 通常我们说this的指向会先考虑this的位置
定义位置this指向
严格模式undefined
普通函数window
对象中的函数函数本身
事件处理函数事件源
箭头函数指向父元素的指向
闭包中指向window

事实上,this指向的问题不应该关注在哪里定义,而要关注在哪里调用。也就是说this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象。

1. 直接调用this,普通模式this指向window;严格模式,this指向undefined

        //普通模式
        let test = function () {
            console.log(this);
        }
        test() ;  //this指向window ;
        //严格模式
        let test = function () {
            "use strict";
            console.log(this);
        }
        test() ;  //this指向undefined ;

2. 通过事件来调用,this指向事件源

        let test = function () {
            console.log(this);
        }
        document.onclick = test ;   //this指向document

3. 对象里的this,分为两种: (1)通过对象函数调用指向对象本身; (2)赋值给变量调用指向window

        //通过对象函数调用
        let obj = {
            name:"张三" ,
            fn(){
                console.log(this);
            }
        }
        obj.fn() ;  //this指向obj
        //赋值给变量调用
        let obj = {
            name:"张三" ,
            fn(){
                console.log(this);
            }
        }
        let myfn = obj.fn;
        myfn() ;   //this指向window ;

4.定时器里的this: (1)如果是回调函数,this会指向window;(2)箭头函数 :没有this绑定 ,箭头函数的this绑定是上层的this绑定

        //回调函数
        document.onclick = function(){
            let that = this ;  //让that储存this指向
            setTimeout(function(){
                console.log(this);  //this指向window
                console.log(that);  //this指向document
            },1000) ;
        }
        //箭头函数
        document.onclick = ()=>{
            setTimeout(()=>{
                console.log(this); //window ;
            },1000) ;  
        }

5. 构造函数或者是类里的this ;指向实例化对象;

        //构造函数中的this
        function Person(name){
            this.name = name ;
            console.log(this);
        }
        Person.prototype.fn = function(){
            console.log(this);
        }
        
        Person();  //this指向window ;
        let zhangsan = new Person("张三");
        zhangsan.fn();   //this指向obj
     
        //类中的this
        class Person{
            constructor(name){
                this.name = name ;
                console.log(this);
            }
            fn(){
                console.log(this);
            }
        }
        let zhangsan = new Person("张三") ;
        zhangsan.fn();  //this指向obj

6.箭头函数没有this绑定,箭头函数的this是上层的this; 7.模块化里的this ;在前端模块化下 是自动变成严格模式

      import "../js/a.js" ;  //this指向window