1👍
The function
creates a new context. You need to switch to arrow function and use this.signOut()
. Simplified example:
timer() {
var counter = -1;
var timeout;
var startTimer = () => {
counter++;
console.log(counter);
this.signOut();
timeout = setTimeout(startTimer, 1000);
};
setTimeout(startTimer, 1000);
}
Moreover, you have two signOut()
methods defined in one class.
0👍
The startTimer
-function does not run in the context of the HeaderComponent
‘s instance.
this
in startTimer
will point to window
when it’s executed as a handler in setTimeout
.
In order to access the the instance of HeaderComponent
, either use an arrow function (as pointed out in an earlier answer. See also Arrow function expressions) which will point this
to the outer context (which is HeaderComponent
‘s instance) or define an identifier in timer
which points to the instance (eg. const self = this;
) and use self
instead of this
in startTimer
.
To apply this to your example (for the sake of consistency, I used var
instead of const
):
timer() {
var counter = -1;
var timeout;
var self = this;
var startTimer = function() { // Don't use a named function here, it only leads to more confusion
counter++;
console.log(counter);
self.signOut(); // Use `this` of the outer context
timeout = setTimeout(startTimer, 10000); // Use the declared identifier
};
// Rest of the method
}
this
is Javascript may be a bit confusing to those who come from different programming languages. If you want to get into more detail, I recommend reading into the MDN reference for this
and into Closures