从JavaScript中的字符串获取导出的单例实例

我有一个ExampleView类,应该是单例。在此类中,我有方法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类需要是单例的。

我知道我可以按照以下方式进行操作,然后通过window['ExampleView'].render()进行调用:

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

但是我真的需要用可调节的ES6来实现它。

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

z983352400 回答:从JavaScript中的字符串获取导出的单例实例

填充全局范围不是ES6的方法。我认为您可以对export

这样操作
//
// Class definition
//
window.ExampleView = new ExampleView();

export default window.ExampleView;
,

您只需导入实例

variable "policy" {
  type        = any
  description = "A mapping of policy to assign to the apim."
  default     = null
}

它将是同一对象。


值得一提的是:单身人士是邪恶的。使用ES模块系统来传递实例有点滥用。

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

大家都在问