0

I don´t get why "this" in this case returns "NaN" :

function Counter() {
  this.num = 0;
  this.timer = setInterval(function add() {
    this.num++;
    console.log(this.num);
  }, 1000);
}

And in this one it refers to "this.value":

function foo() {
    this.value = 'Hello, world';

    this.bar = function() {
        alert(this.value);
    }
}

var inst = new foo();
inst.bar();

I get that in the first case "this" is pointing to the Window object, I just don´t get why that´s the case.

Hernan Ariel
  • 243
  • 2
  • 7

2 Answers2

1

Inside setInterval this will be completely new and it will have no idea about Counter. You can use bind to pass the context this to setInterval

function Counter() {
  this.num = 0;
  this.timer = setInterval(function add() {
    this.num++;
    console.log(this.num);
  }.bind(this), 5000);
}

Counter()

Alternatively you can also use arrow function

function Counter() {
  this.num = 0;
  this.timer = setInterval(() => {
    this.num++;
    console.log(this.num);
  }, 5000);
}

Counter()
brk
  • 43,022
  • 4
  • 37
  • 61
0

The setInterval function barely looks like this:

 function setInterval(callback, time, ...args) {
   // native complicated code
   callback(...args);
 }

What matters here is the call (callback(...)), as JS determines the context by how you are calling the function. In your second example the context of bar is inst as you call it as inst.bar(), so you directly tell js what this is. If you call a function direclty, e.g.

 const bar = inst.bar; 
 bar(); // call without context

you don't specify a context, and therefore this defaults to window

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120