箭头函数和this的指向

657 阅读1分钟

一、定义函数的方式

const test = function () {}

二、对象字面量中定义函数

const obj = {
  test: function () {}
}

三、ES6中的箭头函数

无参数

const test = () => {}

两个参数

const sum = (num1,num2) => {
  return num1 * num2
}

一个参数

const power = num => {
  return num * num
}

代码块中只有一行代码时可以省略花括号

const sum = {num1,num2} => return num1 * num2

四、this

1、无箭头函数

<script>
setTimeout(function () {
  console.log(this)
},1000)
</script>
Window

2、箭头函数

<script>
  setTimeout(() => {
    console.log(this)
  }, 1000)
</script>
Window

3、对象中定义函数

const obj = {
  test() {
    setTimeout(function () {
      console.log(this)
    })
    setTimeout(() => {
      console.log(this)
    })
  }
}
Window
{test: f}

对象中无箭头函数输出依旧是Window,但箭头函数输出为obj对象。

4、对象中的嵌套函数

const obj = {
  test() {
    setTimeout(function () {
      setTimeout(function () {
        console.log(this)
      })//window

      setTimeout(() => {
        console.log(this)
      })//window
    })
					
    setTimeout(() => {
      setTimeout(function () {
        console.log(this)
      })//window

      setTimeout(() => {
        console.log(this)
       })//obj
    })
  }
}
Window
Window
Window
{test: f}

结论

箭头函数中的this引用的是最近作用域中的this,是向外层作用域中,一层层查找this,直到有this的定义。