码迷,mamicode.com
首页 > 其他好文 > 详细

箭头函数与this指向问题

时间:2020-05-24 09:36:19      阅读:37      评论:0      收藏:0      [点我收藏+]

标签:define   his   window   fun   undefined   UNC   设计   ons   严格   

箭头函数中this的指向问题

  1. 箭头函数不会改变this的指向,在它外面拿到的this是什么,它里面获取到的就是什么
  2. setTimeout方法挂载在window上面,高程中写道,超时调用的代码都是在全局作用域下执行,非严格模式下this指向window对象,严格模式下为undefined
  3. 老的通过闭包获取this的方法,都可以通过箭头函数来替换
// 箭头函数不会改变this指向

const obj = {
  name: ‘xcc‘,
  func: function() {
    console.log(‘---1---‘, this)
  },
  func1: () => {
    console.log(‘---2---‘, this)
  },
  func2: function() {
    console.log(‘---3---‘, this)  // { name: ‘xcc‘, ...}
    setTimeout(function() {
      console.log(‘---4---‘, this)
    }, 1000)
  },
  func3: function() {
    setTimeout(() => {
      console.log(‘---5---‘, this)
    }, 1500)
  },
  func4: function() {
    const _this = this
    setTimeout(function() {
      console.log(‘---6---‘, _this)
    }, 2000)
  }
}

obj.func()  // { name: ‘xcc‘, func: [Function: func], func1: [Function: func1] }

// 箭头函数没有this的机制,在箭头函数外面拿到的是什么,在里面拿到的就是什么
obj.func1() // {}

console.log(this) // {}


obj.func2()

// setTimeout方法是挂在window对象下的。《JavaScript高级程序设计》第二版中,
// 写到:“超时调用的代码都是在全局作用域中执行的,因此函数中this的值在非严格模式下指向window对象,在严格模式下是undefined”
// 箭头函数中的this始终都是指向当前作用域的this
obj.func3() // ---5--- { name: ‘xcc‘, ...}


// 采用闭包来获取this
obj.func4() // ---6--- { name: ‘xcc‘, ...}

箭头函数与this指向问题

标签:define   his   window   fun   undefined   UNC   设计   ons   严格   

原文地址:https://www.cnblogs.com/sk-3/p/12945353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!