我想导出一个从特定父级“动态”继承的类:
// moduleA
import {localConstructor} from 'aPackage';
const globalCondition = () => {
if (window.GlobalConstructor) {
return window.GlobalConstructor;
} else {
return localConstructor;
}
}
export default class extends globalCondition() {
...
}
// moduleB
import Module from 'moduleA';
const m1 = new Module(); // use local constructor
window.GlobalConstructor = ...;
const m2 = new Module(); // use global constructor
但是,globalCondition
仅在“导出”时被调用,因此我无法即时调整对象的类型。
答案 0 :(得分:0)
如果导出的类应该依赖于某些动态条件,则应为工厂功能:
// moduleA
import {localConstructor} from 'aPackage';
export default () => {
return class extends (window.GlobalConstructor || localConstructor) {...}
}
// moduleB
import moduleFactory from 'moduleA';
const Module = moduleFactory();
const m1 = new Module(); // use local constructor
通过window
在ES模块之间进行通信不是一个好习惯。代替设置window.GlobalConstructor = ...
,可以将构造函数传递给函数。这是常规的混合食谱:
// moduleA
import {localConstructor} from 'aPackage';
export default (Constructor = localConstructor) => {
return class extends Constructor {...}
}
// moduleB
import moduleFactory from 'moduleA';
const Module = moduleFactory(...);
const m2 = new Module(); // use global constructor