I have problems with the this
reference in Javascript (I am an old java developer :) ). I have a service class which is using a this
reference inside one method:
export class SomeService {
constructor(private _resource) { }
loadData(){
return this._resource.readData();
}
}
I try to build a base class on top of this kind of services. For this reason I want to use a reference to this method like that:
export class BaseClass {
constructor(
public loadFunction: () => any
) { }
call(){
this.loadFunction();
}
// ....
}
export class MyLoader extends BaseClass {
constructor() {
super(
customerService.loadCustomers
)
}
}
The this
reference in SomeService
will reference the MyLoad
instance. I can change the example above and extend the constructor of the Baseclass with an additional parameter of the context and use "apply" like:
export class BaseClass {
constructor(
public loadFunction: () => any,
public loadContext : any
) { }
call(){
this.loadFunction.apply(this.loadContext)
}
// ....
}
But it feels like repeating myself. Is that the best (only?) way to archive this?