从字符串名称中要求JS模块的新实例

RequireJS new instance of a module from a string name

本文关键字:新实例 实例 模块 JS 字符串      更新时间:2023-09-26

我有几个模块,我想从字符串中实例化对象。当类/对象等在全局作用域window 上时,这通常很容易

new window["MyClass"]()

使用requireJS时,模块不在window作用域中,如果在类中,则不在this上。

你知道我需要什么范围吗?

define(['testclassb'], function(TestClassB) {
  var TestClassA, testclassa;
  TestClassA = (function() {
    function TestClassA() {
      console.log("A");
      new this["TestClassB"](); #errors with undefined function
      new window["TestClassB"](); #errors with undefined function
      new TestClassB(); #works fine
    }
    TestClassA.prototype.wave = function() {
      return console.log("Wave");
    };
    return TestClassA;
  })();
  testclassa = new TestClassA();
  return testclassa.wave();
});

我有几个模块,我想从字符串实例化对象

这基本上是个坏主意,表明有代码气味。你真的需要吗?

你知道我需要什么范围吗?

TestClassB局部变量,无法通过名称访问。由于您已经静态地将testclassb声明为依赖项,因此没有理由不使用静态变量TestClassB

然而,require.js允许您同步require()已经加载的模块,因此您也可以使用

new (require("testclassb"))();