Method inside a class

Why is the method that has a setTimeout() only gets executed twice?
Here is the pen
It works normally when I use arrow functions.

What do you expect to happen? It’s set up to only run twice now, once on your window load, and the other when you manually call the output function again (in the output function). That’s 2 times.

Hi @Chronzam, that’s because when passing this.output to setTimeout() directly, it will be called in the context on the window to which this will then refer; hence, this.message is undefined the 2nd time (as is this.output).

With arrow functions OTOH the this binding will be preserved; another way would be to explicitly bind(this) like so:

// Essentially the same as
window.setTimeout(() => this.output())

A common approach would be to already do so in the constructor, so that this.output will always have the desired this binding:

class SetTimeout {
  constructor (message) {
    this.message = message
    this.output = this.output.bind(this)

  output () {
    console.log(`output this: "${this.message}"`)
    window.setTimeout(this.output, 3000)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.