Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use 'this' for a generic method function

I’m not sure what the terminology is for this, so apologies if the title is completely off.
I am trying to use the ‘this’ of a method but it’s returning ‘undefined’ when I’m running the code.

I want it to loop through each ‘api’ and call it, then I can go in and do something with the result. Each API can have different parameter data

enum APIPermissions{ HIGH, LOW };
class Api{
  baseurl: string;
  constructor(admin: boolean){
    if(admin){
      this.baseurl = 'localhost';
    }else{
      this.baseurl = 'admin.localhost'
    }
  }

  api1(param1: string){
    return this.baseurl+'/api1 data';
  }

  api2(param1: string, param2: string){
    return this.baseurl+'/api2 data';
  }

  api3(json: any){
    return this.baseurl+'/api3 data';
  }
}
const api = new Api(true);
const data = [
{
    func: api.api1,
    params: ['test1'],
    permissions: [APIPermissions.LOW]
},
{
    func: api.api2,
    params: ['test1', 'test2'],
    permissions: [APIPermissions.HIGH]
}
]
  
for(const d of data){
    const result = d.func('a','b'); // d.params doesn't work
    console.log(result);
    // Check result and do something
}

It’s outputting:
"undefined/api1 data"
"undefined/api2 data"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but I would be expecting "admin.localhost/api1 data". I checked the Typescript docs but the example they give is a bit confusing.
I also don’t know how to get the d.func() part correct as it’s expecting 2 parameters and any help on this too would be appreciated.

>Solution :

Javascript is a bit more dynamic than other languages. When you get a function reference from an object, it’s just the function without a context.

To fix this you need to explicitly bind the functions to an object instance, this will fix the issue you have:

const data = [
  {
    func: api.api1.bind(api),  // bind function to the api object
    params: ['test1'],
    permissions: [APIPermissions.LOW],
  },
  {
    func: api.api2.bind(api),    // bind function to the api object
    params: ['test1', 'test2'],
    permissions: [APIPermissions.HIGH],
  },
];

You can read a bit more about this in here this is not bound.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading