箭头函数

2019-02-18  本文已影响0人  春饼sama

箭头函数

箭头函数能让this的指向固定化

function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // 箭头函数
  setInterval(() => this.s1++, 1000);
  // 普通函数
  setInterval(function () {
    this.s2++;
  }, 1000);
}

var timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0

分析:
1)第一个setInterval()中使用了箭头函数,箭头函数使this绑定定义时所在的作用域,this指向固定
2)第二个setInterval()中使用了普通函数,只想运行时的作用域 即全局对象

箭头函数转成 ES5 的代码

// 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 引用外部this
除了this,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:arguments、super、new.target

箭头函数的不适合场景

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

箭头函数中的this指向了window,静态化了
普通函数 this指向cat

需要动态this 难怪addEventListenr中不能使用箭头函数

// 这里this指向了window  会报错
let button = document.getElementById('press');
button.addEventListener('click', () => {
  this.classList.toggle('on');
});

修改为:
button.addEventListener('click', function(e) {
  this.classList.toggle('on');
});

结论:回调函数里面使用了this的不要使用箭头函数

上一篇 下一篇

猜你喜欢

热点阅读