我们知道箭头函数没有自己的this,箭头函数的this取决于箭头函数在哪儿定义,而非箭头函数执行的上下文环境。

总之,箭头函数与普通函数的其他重要区别:

  1. 对this 的关联:函数内置 this 的值,取决于箭头函数在哪儿定义,而非箭头函数执行的上下文环境
  2. this 不可变:.call()/.apply()/.bind()无法改变箭头函数中this的指向
  3. new不可用:不能作为构造函数:不能使用new来调用
  4. 没有arguments对象:没有自己的super、arguments和new.target绑定
  5. 没有原型对象 prototype
  6. 不可以使用yield命令,因此箭头函数不能用字Generator函数中


  1. const obj = {
  2. a: function() {
  3. console.log(this);
  4. },
  5. b: () => {
  6. console.log(this);
  7. }
  8. };
  9. obj.a(); //输出obj
  10. obj.b(); //输出window

箭头函数 优于 普通函数

什么时候箭头函数更好?

比如react的时候,我们使用箭头函数,就不需要手动绑定this了

  1. class Toggle extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {isToggleOn: true};
  5. // 为了在回调中使用 `this`,这个绑定是必不可少的
  6. // this.handleClick = this.handleClick.bind(this);
  7. }
  8. handleClick() {
  9. this.setState(state => ({
  10. isToggleOn: !state.isToggleOn
  11. }));
  12. }
  13. render() {
  14. return (
  15. <button onClick={() => {
  16. // console.log(this); # 箭头函数让this指向了 toggle实例
  17. this.handleClick();
  18. }}>
  19. # 第二种手动bind的写法
  20. <button onClick={this.hanleClick}>
  21. {this.state.isToggleOn ? 'ON' : 'OFF'}
  22. </button>
  23. );
  24. }
  25. }

比如函数式编程的时候, 代码清晰,一点也不拖泥带水

# 柯里化
const addCurry = function(a){
  return function(b){ 
    return function(c){ 
      return a+b+c;
    }
  }
}

const addCurry = a => b => c => a + b + c;

调用
addCurry(10)(5)(3) = 18

普通函数 优于 箭头函数

比如vue的时候,必须要function而不是箭头函数
1、与原型方法、对象方法、构造函数有关

# vue
<template>
  <div id="app">
    <button v-on:click="getData">点击</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      name: "hello",
    };
  },
  methods: {
    getData() { # getData必须是function,箭头函数 this 则会是undefined
      console.log(this.name) // this指向当前vue实例
      this.$nextTick(function () { # $nextTick里的回调,写箭头函数 和 普通函数都可以
        // dom更新了                                 # this都是指向的 当前component实例
        // this.doSomethingElse();
      });
    }
  }
};
</script>

2、点击事件回调

const button = document.getElementById('myButton');
button.addEventListener('click', () => { # 此时使用普通函数 this指向按钮明显更方便
    console.log(this === window); // => true
    this.innerHTML = 'Clicked button';
});