user5222086
user5222086

Reputation:

How to call an identically-named parent function?

Consider the following code:

class Base {
   constructor() {
      let _myPrivateData = 'Base';
      this.print = () => { console.log(_myPrivateData); };
   }
};

class Derived extends Base {
   constructor() { 
      super();
      this.print = () => { this.print(); console.log('Derived'); };
      //                   ↑↑↑↑
   } 
};

I've avoided the methods notations to enforce the privacy of the encapsulated data (i.e. the _myPrivateData).
Using this (at the marked section) would cause an "infinite recursion". The super keyword cannot be used there as it's only valid inside methods. I've also tried the Base.prototype.print() to no avails!

So, how to invoke the print() function defined in the Base class, from inside of an identically-named-function in the Derived class?

Upvotes: 2

Views: 58

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386604

You may save the current value of the this.print before overriding it (where it still points to the print defined in the Base class):

class Base {
   constructor() {
      let _myPrivateData = 'Base';
      this.print = () => { console.log(_myPrivateData); };
   }
};

class Derived extends Base {
   constructor() { 
      super();
      let print = this.print; // <-- Save the current value before overriding
      this.print = () => { print(); console.log('Derived'); };
      //                   ↑↑↑↑↑
   } 
};

var x = new Derived();

x.print();

Upvotes: 3

Related Questions