前端JS必备知识点:如何正确的判断this的指向?

如何正确的判断this的指向?

this的指向问题在JavaScript中是非常重要的,如果用一句话说明 this 的指向,那么就是: 谁调用它,this 就指向谁。

1、普通函数(this指向window)默认绑定;严格模式下会抛出错误undefined('use strict')

    var age = 18;
    function fun() {
        console.log(this.age);
    }
    fun();//18  this指向window

2、对象函数(this指向该方法所属对象)

var o = {
        sayHi:function(){
            console.log(this);   
        }
    }
    o.sayHi();//{sayHi: ƒ}

3、构造函数(如果没有return,则this指向这个对象实例;如果存在return返回一个对象,则this指向返回的这个对象)

    function Star(uname,age){
        this.uname = uname;
        this.age = age;
    }
    let a = new Star('xiaoming',18);
    console.log(a);//Star {uname: "xiaoming", age: 18} 
    function Star(uname,age){
        this.uname = uname;
        this.age = age;
        let obj = {
            age:10
         }
        return obj;  
    }
    let a = new Star('xiaoming',18);
    console.log(a);//{age: 10}

4、绑定事件函数(this指向的是函数的调用者,指向了接收事件的HTML元素

     var btn = document.querySelector('button');
     btn.onclick = function () {
         console.log(this);  //btn <button>点击</button>
     }

5、定时器函数(this指向window)

setTimeout(function(){
        console.log(this);
    }, 2000);//this指向window

6、立即执行函数(this 指向window)

(function(){
        console.log(this); //this指向window
    })(); 

7、箭头函数(不绑定this关键字,指向的是函数定义位置的上下文this)

    const obj ={name:'xiaoming'};
    function fn(){
        console.log(this);//{name: "xiaoming"}
        return ()=>{
            console.log(this);//{name: "xiaoming"}
        }
    }
    const resFn = fn.call(obj);
    resFn();

8、显示绑定:函数通过call()、apply()调用,bind()方法绑定,this指向的就是指定的对象;

    function fun() {
        console.log(this.age);
    }
    var person = {
        age: 20,
        fun
    }
    var age = 28;
    var fun = person.fun;
    fun.call(person);   //20
    fun.apply(person);  //20
    fun.bind(person)(); //20

如果这些方法传入的第一个参数是 undefined 或者 null,严格模式下 this 指向为传入的值undefined / null;非严格模式下指向window(全局);

    function fun() {
        console.log(this.age);
    }
    var person = {
        age: 20,
        fun
    }
    var age = 28;
    var fun = person.fun;
    fun.call(null);   //28

9、 隐式绑定:函数的调用是在某个对象上触发的,即调用位置上存在上下文对象(相当于对象函数中的this指向)。典型的隐式调用为: xxx.fn()

     function fun() {
        console.log(this.age);
    }
    var person = {
        age: 20,
        fun
    }
    var age = 28;
    person.fun(); //20 隐式绑定

 


版权声明:本文为weixin_42721322原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。