ES6箭头函数与this

本文探讨了JavaScript中普通函数与箭头函数的this指向差异。在普通函数中,this取决于函数调用方式,而在箭头函数中,this保持定义时的上下文。通过示例展示了在异步操作如setTimeout中,如何利用闭包保存this引用以保持其指向。此外,分析了this在不同场景下的变化及其对代码执行的影响。
摘要由CSDN通过智能技术生成

 普通函数内部的this指向的是函数运行时所在的对象,this指向是可变的:

const person = {
  name: 'Lily',
  sayHi: function () {
    console.log(`This is ${this.name}`);
  }
}
person.sayHi();  // This is Lily

箭头函数内部没有自己的this对象,内部的this就是函数定义生效时其上层作用域中的this:

const person = {
  name: 'Lily',
  sayHi: () => {
    console.log(this);  // {}
    console.log(`This is ${this.name}`);
  }
}
console.log(person.this);  // undefined
person.sayHi();   // This is undefined

--------------------------------------------------------------------------------------------------------------------------------

普通函数this指向的可变性:

const person = {
  name: 'Lily',
  sayHiAsync: function () {
    console.log(this);
    setTimeout(function () {
      console.log(this);
      console.log(this.name);
    }, 1000)
  }
}
person.sayHiAsync();

// 输出结果为:
// { name: 'Lily', sayHiAsync: [Function: sayHiAsync] }

// Timeout {
//   _idleTimeout: 1000,
//   _idlePrev: null,
//   _idleNext: null,
//   _idleStart: 48,
//   _onTimeout: [Function],
//   _timerArgs: undefined,
//   _repeat: null,
//   _destroyed: false,
//   [Symbol(refed)]: true,
//   [Symbol(asyncId)]: 6,
//   [Symbol(triggerId)]: 1
// }

// undefined



// 改变this指向的可变性const _this = this:
const person = {
  name: 'Lily',
  sayHiAsync: function () {
    console.log(this);
    const _this = this;
    setTimeout(function () {
      console.log(this);
      console.log(_this.name);
    }, 1000)
  }
}
person.sayHiAsync();

// 输出结果为:
// { name: 'Lily', sayHiAsync: [Function: sayHiAsync] }
// Timeout {
//   _idleTimeout: 1000,
//   _idlePrev: null,
//   _idleNext: null,
//   _idleStart: 46,
//   _onTimeout: [Function],
//   _timerArgs: undefined,
//   _repeat: null,
//   _destroyed: false,
//   [Symbol(refed)]: true,
//   [Symbol(asyncId)]: 6,
//   [Symbol(triggerId)]: 1
// }
// Lily

箭头函数中this指向的固定性:

const person = {
  name: 'Lily',
  sayHiAsync: function () {
    console.log(this);
    setTimeout(() => {
      console.log(this);
      console.log(this.name);
    }, 1000)
  }
}
person.sayHiAsync();

// 输出结果为:
// { name: 'Lily', sayHiAsync: [Function: sayHiAsync] }
// { name: 'Lily', sayHiAsync: [Function: sayHiAsync] }
// Lily

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值