BartoszK
BartoszK

Reputation: 182

Is there a way to get this/context out from method?

I have done this function in JavaScript:

var syncCall = function( cb, obj, fn ) {
   var params = [];
   for( var i=3; i< arguments.length; i++ ) {
      params.push( arguments[i] );
   }
   fn.apply( obj, params )
      .onReject( function( result ){
         console.error( result );
       } )
       .onFulfill( function( result ){
          if( cb != undefined && cb != null ) {
             cb( result );
          }
       });
};

The problem is, that I have to passs obj param into syncCall function, to set proper context ofthisinsidefn` when it is called.

In my case, fn is always a method/function, that is stored in one of obj properties. So normally when executing for example obj.myFunctionname(), the this operator inside myFunctionname refers to obj. I am wondering, if I can take an adventage of that fact. Meaning, when having fn as a parameter to syncCall, take somehow the context ( which is obj ) and pass it properly to apply() function as first parameter (thus, resign from having obj as second input parameter in syncCall() )

Upvotes: 1

Views: 78

Answers (1)

thesebas
thesebas

Reputation: 26

If you want to get rid of obj param fn should be context (this) agnostic because you should be able pass as fn any callable (eg. anonymous function that do not use this) so 1) pass function bound to obj or 2) leave context as is and call .apply w/o context param fn.apply(null, params):

1) if called anywhere bound fn to obj:

syncCall(cb, fn.bind(obj))

or

2) if called inside obj context leave fn as is

obj = {

 fn: function(){
  // some logic to be done in syncCall
 },

 someObjMethod: function(){
   syncCall(cb, this.fn); //here this == obj and will be inside syncCall
 }
}

Upvotes: 1

Related Questions