You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have an ES6 Class function that I'd like to invoke as a callback function, but it loses the scope of this when I call it with timer(callback).
Any way we can pass a custom variable to the callback function? I'm not quite sure how the syntax would even look, as I wouldn't want to override the delay and time variables.
The text was updated successfully, but these errors were encountered:
Did you consider using function.bind or a closure? Say you have an instance of your class (here described as a literal, but the use of ES6 classes or fields inherited properties doesn’t affect the solution):
varfred={hello: function(){console.log("Hi, my name is "+this.name+".");returntrue;},name: "Fred"};
Invoking the hello method:
fred.hello();// prints "Hi, my name is Fred.", returns true
Invoking this method by timer using a closure:
timer(function(){returnfred.hello();});
Invoking this method by timer using function.bind:
timer(fred.hello.bind(fred));
Note that you can also use a closure to pass extra arguments to your callback. For example, say you have a function:
functionhello(name){console.log("Hi, my name is "+name+".");returntrue;}
I have an ES6 Class function that I'd like to invoke as a callback function, but it loses the scope of
this
when I call it withtimer(callback)
.Any way we can pass a custom variable to the callback function? I'm not quite sure how the syntax would even look, as I wouldn't want to override the delay and time variables.
The text was updated successfully, but these errors were encountered: