箭头函数

2019-12-10  本文已影响0人  me_coder

箭头函数没有自己的this,导致内部的this就是外层代码块的this。正是因为它没有this,所以也就不能用作构造函数。
一个示例:

// ES6
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

// ES5
function foo() {
  var _this = this;

  setTimeout(function () {
    console.log('id:', _this.id);
  }, 100);
}

除了没有this,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:argumentssupernew.target
另外,由于箭头函数没有自己的this,所以当然也就不能用call()apply()bind()这些方法去改变this的指向。

(function() {
  return [
    (() => this.x).bind({ x: 'inner' })()
  ];
}).call({ x: 'outer' });
// ['outer']

不适用的场合

1、定义对象的方法,且该方法内部包括this

const cat = {
  lives: 9,
  jumps: () => {
    this.lives--;
  }
}

此时,this指向全局对象,而不使用箭头函数的时候this指向cat对象。
2、需要动态this的时候

var button = document.getElementById('press');
button.addEventListener('click', () => {
  this.classList.toggle('on');
});

这个this也指向全局对象,而普通函数则指向被点击的按钮。

上一篇下一篇

猜你喜欢

热点阅读