Js中常见this指向问题

无论是工作或者面试中,this指向问题是经常遇到的。所以这篇文章把常见的指向问题列出来给大家,避免踩坑。首先我们要知道,在函数中this到底取何值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不了,也就是说,this的指向完全取决于函数调用的位置。因为this的取值是作用域环境的一部分,每次调用函数,都会在不同的作用域环境。

1:全局环境中

在浏览器环境严格模式中(区别于node),this默认指向window。立即执行函数,默认的定时器等函数,this也是指向window。

    console.log(this === window) // true
    function fn(){
        console.log(this === window)
    }
    fn() // true
    (function(){
        console.log(this === window) // true
    })()
    setTimeout(function() {
      console.log(this === window); //true
    }, 500)
2:对象函数中

如果函数作为对象的一个属性被调用时,函数中的this指向该对象。

    var x = 10 // 相当于 window.x = 10
    var obj = {
        x: 20,
        f: function(){
            console.log(this.x)
        },
        s: function(){
            console.log(this.x) // 20
            function fn(){
              console.log(this.x)
            }
            return fn  // 函数f虽然是在obj.fn内部定义的,但是它仍然是一个普通的函数,this仍然指向window
        }
    }
    var fn = obj.f
    fn()  // 10 
    obj.f() // 20
    obj.s()() // 10

首先调用fn()为什么结果为10,因为新建了变量fn,相当于fn = function(){ console.log(this.x)}, 函数中this默认指向window,故输出为10。而 obj.f() 中this 指向obj,所以this.x = obj.x, 输出结果为20。

3:构造函数中

构造函数创建的实例的属性指向构造函数的prototype。

    function Man(name){
        this.name =  name
    }
    Man.prototype.getName = function(){
        // this指向 Man
        return this.name
    }
    const tom = new Man('tom')
    console.log(tom.getName()) // 'tom'
    
    // 切记请勿修改构造函数的返回值,将会改变默认指向,比如
    function Man(name){
        this.name =  name
        return {
            name: 'lily'
        }
    }
    Man.prototype.getName = function(){
        // this指向 Man
        return this.name
    }
    const tom = new Man('tom')
    console.log(tom.name) // 'lily'
    

4:箭头函数中

箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的,箭头函数中的this取决于该函数被创建时的作用域环境。

    // 第一种情况
    var x= 10
    var obj ={
      x: 20, 
      f1: function(){
        console.log(this.x)
      },
      f2: () => {
        console.log(this.x) // 指向 window
      }
    }
    obj.f1() // 20
    obj.f2() // 10
    
    // 第二种情况
    var name = "jack"
    var man = {
      name: 'tom',
      f1: function(){
        // 这边的this和下面的setTimeout函数下的this相等
        var that = this
        setTimeout(()=>{
          console.log(this.name, that === this) // 'tom' true
        }, 0)
      },
      f2: function(){
        // 这边的this和下面的setTimeout函数下的this不相等
        var that = this
        setTimeout(function(){
          console.log(this.name,  that === this) // 'jack' false
        }, 0)
      }
    }
    man.f1()  // 'tom' true
    man.f2() // 'jack' false

setTimeout默认指向window,但是,在箭头函数中,this的作用域环境在man内,故this指向了man。也就是说此时的this可以忽略外围包裹的setTimeout定时器函数,看上一层及的作用域。

5:dom节点中

特别在是react中jsx语法中,我们通常要改变dom的this指向,不然获取不到指定的执函数。所以通常需要在函数声明使用bind绑定事件。

    // html
    <button id="btn">myBtn</button>
    
    // js
    var name = 'window'
    var btn = document.getElementById('btn')
    btn.name = 'dom'
    var fn =  function (){console.log(this.name)}
    btn.addEventListener('click', f()) // this指向 btn
    btn.addEventListener('click', f.bind(obj)) //  this指向 window

本文涉及到的案例是相对比较常见,如果想更加深入的理解this,可以参考github上的一篇文章 ☛ 传送门

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值