Arrow functions and ordinary functions

The arrow function allows this in setTimeout to be bound to the scope where it is defined, rather than pointing to the scope where it is run. For example:

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); // Output 3 after 3.1s

setTimeout(() => console.log('s2: ', timer.s2), 3100); // Output 0 after 3.1s

In the above code, this in the first setInterval is bound to the scope where it is defined (Timer function), and this in the second setInterval is bound to the scope where it is run (global object); in the second setInterval This.s2 is actually the real-time global s2. It was originally undefined and turned into NaN after using ++. Therefore, when timer.s2 is printed, the timer's s2 has not been updated and 0 is output;

Note: The arrow function can make this point fixed, such as the first setInterval in the chestnut above.

 

Guess you like

Origin blog.csdn.net/khadijiah/article/details/103017368