箭头函数和普通函数

箭头函数可以让setTimeout里面的this绑定定义时所在的作用域,而不是指向运行时所在的作用域,举个栗子:

function Timer() {

  this.s1 = 0;

  this.s2 = 0;

  setInterval(() => {

    this.s1++;

  }, 1000);

  setInterval(function () {

    this.s2++;

    console.log('get here', this.s2); // NaN

  }, 1000);

}

let timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3100); // 3.1s后输出3

setTimeout(() => console.log('s2: ', timer.s2), 3100); // 3.1s后输出0

上面的代码中,第一个setInterval里面的this绑定定义时所在的作用域(Timer函数),第二个setInterval里面的this绑定运行时所在的作用域(全局对象);第二个setInterval里面的this.s2其实时全局的s2,本来时undefined,用了++变成了NaN,所以打印timer.s2,timer的s2是没有被更新的,输出0;

注:箭头函数可以让this指向固定化,例如上面栗子里的第一个setInterval一样

猜你喜欢

转载自blog.csdn.net/khadijiah/article/details/103017368
今日推荐