考虑以下代码:
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
函数呢?