0

I was trying to execute something like this:

class A {
  functionA() {
    setTimeout(function() {
      console.log(this);
    }, 1000)
  }
}

const a = new A();
a.functionA();

But this always refers to the window object. I know that you could setup something like var a = this, but is there a more elegant way to pass this down from the object to the inner function?

1
  • 1
    functionA() { setTimeout(console.log, 3000, this); ... make a proper use of setTimeout. Commented May 16, 2020 at 20:42

3 Answers 3

2

You can use an arrow function instead of a regular function to keep the this context:

class A {
  functionA() {
    setTimeout(() => {
      console.log(this);
    }, 1000)
  }
}

const a = new A();
a.functionA();

Another way is to .bind(this) which will create a function with bounded this context:

class A {
  functionA() {
    setTimeout((function() {
      console.log(this);
    }).bind(this), 1000)
  }
}

const a = new A();
a.functionA();

Sign up to request clarification or add additional context in comments.

Comments

1

In order to meet the OP's expectation of coming up with a more elegant way I suggest the proper usage of setTimeout before thinking about any other approach ...

class A {
  constructor() {
    this.delay = 3000;
  }
  functionA() {
    setTimeout(console.log, this.delay, this);
  }
}

const a = new A();
a.functionA();
.as-console-wrapper { max-height: 100%!important; top: 0; }

Comments

0

Along with Sebastian's answer, another solution can be

class A {
  functionA() {
    const that = this
    setTimeout(function() {
      console.log(that);
    }, 1000)
  }
}

a = new A();
a.functionA();

2 Comments

... scope or context ?.. The OP, btw, is aware of this solution. It was ask for a more elegant way.
context, let's switch back to our favorite 'that' so that there's no confusion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.