• JavaScript provides you with standard means to ensure the desired context:

    • You can pass parameter for the function in

      setTimeout(function(_, otherParms,...){
      _.memberOfContextObject;
      _.memberOfContextObject();
      }, timeoutTimeInMS, contextObject, otherParms,...);
      
    • Alternative is to bind the function and then pass to `

      setTimeout(function(otherParms,...){
      this.memberOfContextObject;
      this.memberOfContextObject();
      }.bind(contextObject), timeoutTimeInMS, otherParms,...);
      
    • 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.

About

Avatar for allObjects @allObjects started