如何调用同名父函数?

考虑以下代码:

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

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

我避免使用methods表示法来强制封装数据(即_myPrivateData)的私密性。
使用this(在标记的部分)将导致“无限递归” super关键字不能在那里使用,因为它仅在方法内部有效。我也尝试过Base.prototype.print()无济于事!

那么,如何从print()类中的同名函数内部调用Base类中定义的Derived函数呢?

a751113604 回答:如何调用同名父函数?

您可以在覆盖this.print的当前值之前保存它的当前值(该值仍指向print类中定义的Base):

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();

本文链接:https://www.f2er.com/2830099.html

大家都在问