箭头函数的this指向问题及其具体使用场景

obj = {
  name:'lili',
  age:20,
  sayAge1:function(){
    // obj调用sayAge1(),则this指向obj,this.name相当于obj.name
    console.log('my name is ' + this.name + ' my age is ' + this.age)
  },
  sayAge2:() =>{
    // 箭头函数的this指向最近的函数的this,而sayAge2()外层没有函数,所以this指向的是window
    console.log('my name is ' + this.name + ' my age is ' + this.age)
  },
  // obj调用sayAge3,那么sayAge3函数的this指向obj,箭头函数的this指向sayAge3中的this,也就指向了obj
  sayAge3:function(){
    setTimeout(()=>{
      console.log('my name is ' + this.name + ' my age is ' + this.age)
    },2000)
  },
  //setTimeout并没有直接调用者,所以function中的this指向window 
  sayAge4:function(){
    setTimeout(function(){
      console.log('my name is ' + this.name + ' my age is ' + this.age)
    },1000)
  }
}
obj.sayAge1()
obj.sayAge2()
obj.sayAge3()
obj.sayAge4()

应用场景:
1、例如定义了一个obj对象,对象里面定义了属性是函数,而函数属性里面又执行了setTimeout函数,需要打印对象中的一些属性值,这个时候可以用箭头函数,因为obj调用函数属性,那么函数属性的this指向obj,而函数属性里面的箭头函数的this指向函数属性的this,就指向了obj
2、在构造函数中,需要在函数内建一个定时器,打印函数内部的this.name,那么使用需要使用箭头函数

var env = 'outside'
function Test() {
    this.env = 'inside';
    setTimeout(()=>{
      console.log("函数内部env~"+this.env)
    },1000)
    setTimeout(function(){
      console.log("函数外部env~"+this.env)
    },2000)
}
const test = new Test();

改变this指向的方法:

  • apply
  • call
  • bind
  • 构造函数实例化new时,this指向新创建的这个实例
  • 构造函数return{对象}时,this指向return的这个对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值