从javascript中的字符串获取导出的singleton实例



我有一个ExampleView类,它应该是singleton。在这个类中,我有一个方法render,我想通过对象名"ExampleView"从另一个js文件调用它。这是代码:

import View from './view';
class ExampleView extends View {
render() {
return `<span>Test</span>`;
}
}
export default new ExampleView(); //<- exporting as singleton and this object I try to get via it's name

首先,我应该从名称"ExampleView"中检索以某种方式导出的单例对象ExampleView,然后调用方法render

class Test {
getInstanceOfModuleByName(name) {
//window[name].render();
}
}

问题是,我找不到任何方法从名称中获取ExampleView实例,但我的ExampleView类需要是一个singleton。

我知道我可以用以下方式完成,然后用window['ExampleView'].render():调用它

ExampleView = {
render: function() {
return `<span>Test</span>`;
}
}

但我真的需要用可模块化的ES6来实现它。

你能解释一下我该怎么做吗?

填充全局范围不是ES6的方法。我想你可以这样对你的export

//
// Class definition
//
window.ExampleView = new ExampleView();
export default window.ExampleView;

您只需导入实例

import whateverYouWantToCallYourViewInstance from './ExampleView'
// snip
return whateverYouWantToCallYourViewInstance.render();

它将是同一个对象。

值得注意的是:单身汉是邪恶的。使用ES模块系统传递实例有点滥用。

最新更新