简体   繁体   中英

Dynamically create instance of class without preloading the class

Is it possible to create a dynamic class without preloading it? I would like to avoid preloading the class, since I'm dynamically importing it. Below is a code example that illustrates what I'm trying to achieve:

  import(namespace).then((DynamicClass) => {
    var classInstance = new DynamicClass();
  }

This currently results in: (node:962) UnhandledPromiseRejectionWarning: TypeError: dynamicClass is not a constructor

When I console.log the DynamicClass, it shows:

{ default: [Function: DynamicClass] }

The class is defined like this:

namespace/index.js

class DynamicClass extends BaseClass {
   //...
}
module.exports = DynamicClass;

It looks like your problem has to do with a misunderstanding of modules and the lesser used dynamic import syntax. You are not importing a class you are importing a ES Module. You can use the imported module to access the exported values of the module using the relevant call based on if your desired value is the default export or not.

If your module is exporting a class by default eg

export default class Class(){...}

You would use the default() function available on the module to get the class definition to init.

const module = await import("module-name")
const obj = new module.default();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM