Skip to content
Advertisement

How to always make “this” keyword to reference the parent class (bind child methods to parent class)?

here is the simplest form of my problem:

JavaScript

I know I can fn.bind(service1) in the mapper function to solve the problem, but as fn is dynamic, I would prefer not to do that.
I have tried searching on how to get the parent class from child method but get no results.

I want mapper to be able to call a method of a class (or object) without loosing the this reference in a readable and straightforward way if possible. mapper is always called in the same context.

Is there a way in javascript to solve this problem ?


What I have tried

JavaScript
JavaScript
JavaScript

Real use case context

In the real use case scenario, the mapper is called api2service. As the name suggests, it is used with expressJs to map api routes to services. Here is a simplified version of the code:

JavaScript

That code is repeated a lot of time and always called in the same context, that’s why I need something readable over the strict respect of good practices.

Advertisement

Answer

Until the bind operator proposal is implemented, there’s not much you can do about this. Apart from your attempts, you can automatically bind methods at construction time (see also https://github.com/sindresorhus/auto-bind):

JavaScript

or use a binding Proxy:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement