admin管理员组文章数量:1335560
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
3 Answers
Reset to default 5There 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}()`);
版权声明:本文标题:javascript - Angular2 typescript create new object dynamically with class name from variable? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742240320a2438789.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论