箭头函数

70 阅读1分钟
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)  //s1: 3: this绑定定义时所在的作用域(Timer函数)
setTimeout(() => console.log('s2:', timer.s2), 3100)  //s2: 0:this指向运行时所在的作用域(全局对象)