admin管理员组

文章数量:1335160

I tried to get to work some sort of:

export class SomeComponent {

  constructor() {

    let className: string = "TheClass";

    /* should be the same as .. = new TheClass() */
    let superSpecial = new className();

  }

}

I have not yet figured out how to do this? Could anyone help me?

I tried to get to work some sort of:

export class SomeComponent {

  constructor() {

    let className: string = "TheClass";

    /* should be the same as .. = new TheClass() */
    let superSpecial = new className();

  }

}

I have not yet figured out how to do this? Could anyone help me?

Share Improve this question edited Mar 27, 2017 at 2:06 user663031 asked Mar 26, 2017 at 23:01 Max SolidMax Solid 1,2633 gold badges21 silver badges32 bronze badges 3
  • Be aware that you can't just do this out of the box. You'll need to store your classes in a collection of some sort and then reference them. – Paarth Commented Mar 26, 2017 at 23:21
  • This is more of a javascript question see stackoverflow./questions/9803947/create-object-from-string – shusson Commented Mar 26, 2017 at 23:22
  • What you are looking for is a "factory"; google for that. – user663031 Commented Mar 27, 2017 at 2:08
Add a ment  | 

3 Answers 3

Reset to default 5

There are a few ways to do this. If your class is in a separate module:

SomeClass.ts

export class SomeClass {

    constructor(arg: string) {
        console.log(arg);
    }
}

App.ts

import * as s from "./SomeClass";

var instance = new s["SomeClass"]("param");

Or using namespaces:

namespace Test {

    export class SomeClass {

        constructor(arg: string) {
            console.log(arg);
        }
    }
}

var instance = new Test["SomeClass"]("param");

This will work for you

export class SomeComponent {

  constructor() {

    // suppose TheClass is the imported class name you want to instantiate
    let className: typeof TheClass = TheClass;

    /* should be the same as .. = new TheClass() */
    let superSpecial = new className(); // you "new" it as normal

  }

You should use square bracket notation:

const classNameStr = 'example';
const myStore = {example: class {}};
const init = new myStore[classNameStr]();
// Or in case you class si global
const classNameStr = 'example';
(window as any).example = class {}; // if your class is already global this line should be deleted. I have put it here just to make the example work
const init = new window[classNameStr]();

Or Eval:

eval(`new ${className}()`);

本文标签: javascriptAngular2 typescript create new object dynamically with class name from variableStack Overflow