js之this到底有什么难的?

215 阅读2分钟

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

前言

今天抽空来总结一下this的指向问题,巩固一下基础知识,就当是面试前的一个小复习了,顺带把和this指向关系密切的call、apply、bind也给做一下总结,看看它们如何使用,到底什么时候该用那个。

this指向的分类

在js中this指向大致可以分为四类,如下

  • demo()
  • ***.demo()
  • demo.call()、demo.apply()、demo.bind()
  • new demo()

this指向一般情况下就以这四种形式来做区分

demo()

这种形式的意思是直接去调用函数,前面或者后面没有做任何的操作,因此不存在this指向的改变,所以this指向全局对象(this默认就是指向全局对象,也就是浏览器中的window)

栗子:

    var a=666 
    function demo(){
        console.log(this.a)
    }
    demo()//666

***.demo()

这种形式的重点就是这个'***',谁调用了函数那么this就指向谁

栗子:

    var a=666
    function demo(){
       console.log(this.a) 
    }
    var obj ={
        a:888,
        demo
    }
    obj.demo()//888

demo.call()、demo.apply()、demo.bind()

call、apply、bind可以改变this的指向,也就是说我们想让this是谁this就可以是谁,如下

    var color = 'white'
    function dog(){
        console.log('dog is',this.color)
    }
    dog()//dog is white
    
    color={
        color:'black'
    }
    dog.call(color)//dog is black
    dog.apply(color)//dog is black

从上面代码可以看到,我们通过call、apply改变了this的指向,但他们两个有什么区别呢? 它们的区别其实就是参数的类型不同,call的参数是多个的,用','隔开,如***.call(color,1,1,2,3);apply的参数是只有两个,如***.apply(color,array),第二个参数必须是一个数组,具体使用方法如下

    //apply可以用在求最大最小值中
    var arr= [3,4,5,22,98]
    Math.min.apply(Math,arr)

call和apply都是在使用的时候才确定this的指向,bind是创建函数的时候就确定了this的指向,如下

    var color = 'white'
    color={
        color:'black'
    }
    demo = function dog(){
        console.log('dog is',this.color)
    }.bind(color)
    
    demo()

call、apply、bind都可以改变this的指向,只是他们有的是使用的时候改变,有的是创建函数的时候就确定了this的指向,它们的相同点是第一个参数都是this要指向的对象。

new demo()

这种是最好识别的,只要记住this指向实例化对象即可

    var type = 'dog'
    function animal(){
        this.type = 'cat'
    }
    var demo = new animal()
    console.log(demo.type)//cat
    //这个animal就相当于构造函数,里面的this.属性就是将来要给实例化对象的属性,所以this指向实例化对象

箭头函数中的this

箭头函数中的this比较特殊,上面我们说this的指向是调用时才会确定(这里要注意是普通函数,不包含箭头函数),但箭头函数中的this是创建的时候就确定了,它指向的是它外层的this的指向