Angular2 typescript使用变量中的类名动态创建新对象?

时间:2017-03-26 23:01:56

标签: javascript class typescript

我试着开始某种工作:

export class SomeComponent {

  constructor() {

    let className: string = "TheClass";

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

  }

}

我还没弄明白怎么做?有谁可以帮助我?

3 个答案:

答案 0 :(得分:4)

有几种方法可以做到这一点。如果您的班级在一个单独的模块中:

<强> SomeClass.ts

export class SomeClass {

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

<强> App.ts

import * as s from "./SomeClass";

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

或使用名称空间:

namespace Test {

    export class SomeClass {

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

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

答案 1 :(得分:0)

这对你有用

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

  }

答案 2 :(得分:-2)

您应该使用方括号表示法:

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]();

或Eval:

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