This works too, but is not as flexible as above options:
function anyFunctionOfThis() {
var _this = this; // create non-this reference of this
setTimeout(function(otherParms,...){
_this.memberOfContextObject;
_this.memberOfContextObject();
}, timeoutTimeInMS, otherParms,...);
As you know, you can defined the function as a named function outside of setTimeout(... or setInterval(... or ..., functionAsCallbackParm,...either as function or 'method of an object' (see object-oriented programming with JS). I use this when I have to provide them as callbacks in multiple places:
var fun = function(otherParms,...) { ... };
var funBound = fun.bind(contextObject);
setTimeout(funBound, timoutTimeInMS, otherParms,...
There are many options and combinations there of you can chose from for the optimal use in your situation.
For the alternative 'this', I use the _this or short form of it _ to indicate that it is about the this / context object. I've also seen that to be used. But I prefer a more eye catching - and short - form, therefore: _ is my choice.
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
JavaScript provides you with standard means to ensure the desired context:
You can pass parameter for the function in
Alternative is to bind the function and then pass to `
This works too, but is not as flexible as above options:
As you know, you can defined the function as a named function outside of
setTimeout(...
orsetInterval(...
or..., functionAsCallbackParm,...
either as function or 'method of an object' (see object-oriented programming with JS). I use this when I have to provide them as callbacks in multiple places:There are many options and combinations there of you can chose from for the optimal use in your situation.
For the alternative 'this', I use the
_this
or short form of it_
to indicate that it is about the this / context object. I've also seenthat
to be used. But I prefer a more eye catching - and short - form, therefore:_
is my choice.