Gabriel
Gabriel

Reputation: 2190

Get method's instance owner

Given a class and an instance of it

var class=function() {
    this.propA=99;
    this.methodA=function() {
        console.log(this.propA);
    };
};

var object=new Class();

I'd like to be able to perform a call to methodA where this will be the instance of it and the example (this.propA) will work. Exactly as

object.methodA.call(object);

but without having any reference to object. Like this in some pseoducode:

var methodToCall=object.methodA;
...
...
methodToCall.call(getInstanceOwnerOf(methodToCall));

The objective of this is to pass methods as callbacks to async functions and keep this as the instance when the method is called.

Some workarounds would be to pass method and object to that async function, or to store this in a local variable, but these are the things I want to avoid.

Upvotes: 2

Views: 292

Answers (1)

brianxautumn
brianxautumn

Reputation: 1162

Use bind to bind to the context you want function called in. Note this returns a NEW function which is not the same as the original.

I usually create the new function and give it a different name but you can do it multiple ways.

To be more specific, you can't be sure this is the class the function is declared in, depends on how you called the function and if you are in strict mode.

an example below:

Fiddle: https://jsfiddle.net/f7af535L/

class SomeClass {
  constructor(someVar) {
    this.myVar = someVar;
    this.publicSayVar = this.sayVar.bind(this);
  }

  sayVar() {
    console.log(this.myVar);
  }


}

var object = new SomeClass("hello");
var testcall = object.publicSayVar;
testcall();

Upvotes: 2

Related Questions