0

I would like to set a property of a Constructorfunction inside a arrowfunction which is a property of the Constructorfunction. Inside the arrowfunction I want to use setTimeout(), which takes a function as argument. In my case a anonymous function.

Thanks in advance :)

function ConstructorFunction(){
    this.statusOptions = {
        idle : 'idle',
        working : 'working'
    };

    this.status = this.statusOptions.idle;

    this.setStatus = () => {
        setTimeout(function(){
            this.status = this.statusOptions.working;
        }, 2000);
    };

}

var instance = new ConstructorFunction();
instance.setStatus();
LukeZz
  • 241
  • 2
  • 6
  • There's no properties set for `ConstructorFunction` in your code. Notice, that `this` in the constructor function refers to the newly-created instances of the constructor, not the constructor itself. – Teemu Oct 18 '18 at 10:40
  • Yes, I am aware of that. But you are correct, I explained that part poorly. Thanks for the clarification :) – LukeZz Nov 01 '18 at 10:42

1 Answers1

2

Change your setTimeout callback to an arrow function in order to let it inherit the outer scope (that is the scope of your Constructorfunction)

this.setStatus = () => {
  setTimeout(() => {
    this.status = this.statusOptions.working;
  }, 2000);
};
Karim
  • 8,454
  • 3
  • 25
  • 33
  • Wow that was very fast! Thank you very much, I don't really know why I didn't stick with arrow functions all the way... – LukeZz Oct 18 '18 at 10:42