How can I access a parent object's method in javascript?

say I had some class hierarchy like below. Is there a way for the engine class to have access to the parent's someMethod() method?

class vehicle{
  constructor(){
    this.eng = new engine();
    ...
  }

  someMethod(a){
    ...
  }
  ...
}



class engine{
  ...
}

Upvotes: 0

Views: 484

Answers (2)

Leroy Stav
Leroy Stav

Reputation: 718

There are a number of ways to go about what you want, and you have to ask yourself: conceptually, how is this supposed to work?

You have to rethink the entire situation. Bottom line is, why does the engine care about what vehicle it is in? The vehicle only cares about what the engine is doing, not the other way around.

So, say you have a start method on the vehicle. It may look like

start() {
  this.engine.start().then(function(infofromengine) {
    console.log('engine started', infofromengine);
  }, function(errorfromengine) {
    console.log('error in engine start', errorfromengine);
  }
}

and in your engine you'd have that start method that returns a Promise and whatever info the vehicle might need to know about the engine;

you might also, upon initializing the engine in the vehicle, set up all sorts of event emitters, and in your vehicle constuctor hook into the emitters.

Taking this one step further, you might have some child components that are supposed to, perhaps, be aware of eachother. So you could "wire them up" in construction. An example contrived from this might be in your vehicle constructor

constructor() {
  this.checkEngineLight = new Light();
  this.engine = new Engine({checkEngineLight});
}

and in engine,

constructor(config) {
  let {checkEngineLight} = config;
  this.engineLight = checkEngineLight;
}

someEngineAction() {
  if (some_error_happens) this.engineLight.toggle(true, someerrorid);
}

there is a reason we are called "software engineers" or "software architects". we don't just write code, we have to consider how the code interacts with all the moving parts.

But to answer your question more directly, in the case where the "engine" absolutely has to have direct access to the "vehicle" you would have to tell the engine about the vehicle... just like how you told it about the check engine light: new Engine(this) and the engine constructor would be constructor(vehicle)

Upvotes: 1

Danyal Imran
Danyal Imran

Reputation: 2605

There are two solutions to this problem

First, if you inherit the properties of a parent like this:

class engine extends vehicle {
  someMethod(a) { // method name has to be the same name as parent, calling super calls vehicle's someMethod(a) method
    super(a); // vehicle.super called
  }
}

or create an instance of vehicle and call the method

class engine {
  someMethod(a) { // can be any name, as long as its using v.someMethod(a)
    const v = new vehicle();
    v.someMethod(a);
  }
}

Upvotes: 0

Related Questions