ES6/ES7 用同名扩展 class

ES6/ES7 extend class with same name

由于模块的条件导入尚未实现,我该如何扩展或覆盖相同的 class:

// I have a main class
// main.js
export default class Main {}

// Main class is used by myClass
class myClass {
  constructor(){
    new Main()
  }
}

// I have an extended main class
// main-extended.js
export default class MainExtended extends Main {}

// the MainExtended is now used by myClass
export class myClass {
  constructor(){
    new MainExtended()
  }
}


// third-class.js
// now I need to do this with any class I can find, 
// preferably with the extended version of both, if both defined
export default class ThirdClass {
  constructor(...args){
    return new myClass(...args)    
  }
}


// destinations

// index.js
import Main, {myClass} from main.js
import ThirdClass from third-class.js


// index-extended.js
import MainExtended, {myClass} from main-extended.js
import ThirdClass from third-class.js



问题是,出于某种原因,编译的 index.js 还包含 myClass 调用 MainExtended,所以我决定只在 [=17] 中包含 ThirdClass =],作为 MainExtended.

的额外功能

但是我还是想知道有没有别的办法

就像 VLAZ 在评论中所说的,我不是 100% 确定你在问什么,但你能做这样的事情吗?

解决方案 1

class MyClass {
  constructor(_main){
    myMain = _main;
  }
}

const regularMain = new MyClass(new Main());
const extendedMain = new MyClass(new MainExtended());