0

My original code was like this:

function Person() {
  this.age = 0;
  console.log(this.age);
  setInterval(function() {
    this.age++;
    console.log(this.age);
  }, 1000);
}

let p = new Person();

The output was something like this:

0
NaN
NaN
.
.
.

But when I changed the callback function to an arrow function it worked:

function Person() {
  this.age = 0;
  console.log(this.age);
  setInterval(() => {
    this.age++;
    console.log(this.age);
  }, 1000);
}

let p = new Person();

This time the output was:

0
1
2
3
.
.
.

The anonymous function couldn't access the constructor variable. Why so?

adiga
  • 34,372
  • 9
  • 61
  • 83
Aniket
  • 153
  • 1
  • 2
  • 8

0 Answers0