Home > Software engineering >  How to call base class method from super class method
How to call base class method from super class method

Time:11-12

my base class:

import { Component, VERSION } from '@angular/core';
import { Feature } from './super.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent extends Feature {
  name = 'Angular '   VERSION.major;
  constructor() {
    super();
  }

  superToCall(value) {
    console.log('value', value);
  }
}

super class:

export class Feature {
  childCalled(value) {
    console.log('child called', value);
  }
}

how to pass the param to superToCall from childCalled method?

Live Demo

CodePudding user response:

Classic OOP pattern: declare super class as abstract with abstract method abstract superToCall(value: unknown):void. Now you can call child's method from parent class with this.superToCall(someValue)

CodePudding user response:

This is helped me:

ParentClass.prototype.myMethod.call(this)

call with params:

import { AppComponent } from './app.component';

export class Feature {
  childCalled(value) {
    AppComponent.prototype.superToCall.call(this, value)
  }
}

CodePudding user response:

Make your parent class (Feature) abstract and add an abstract function superToCall (which the children must implement):

export abstract class Feature {
  childCalled(value) {
    console.log('child called', value);
    this.superToCall(value);
  }

  abstract superToCall(value);
}

All children (which extend Feature) must now implement the abstract method superToCall:

export class AppComponent extends Feature {
  constructor() {
    super();
  }

  override superToCall(value) {
    console.log('value', value);
  }
}

Stackblitz example

CodePudding user response:

You can just test on the parent if it exists on the child and then call it :

export class Feature {
  childCalled (value) {
    if (this.superToCall)
      this.superToCall(value)
    else
      console.error(`superToCall does not exist on ${ this }`)

  }
}
  • Related