JavaScript:如何使用变量作为构造函数名称

4
我需要从另一个函数中获取参数,该参数将用作创建新对象实例的构造函数名称:
function foo(bar) {
    thing.push(new bar(arg1, arg2);
}

如何创建一个由字符串bar构造的新对象实例?


1
它会是一个字符串吗?为什么不直接将引用传递给构造函数呢? - Andrew Li
2个回答

2
您可以传递构造函数。

var Bar = function (a1,a2) {
 this.a1 = a1;
 this.a2 = a2;
}

function foo(bar) {
    
    var obj = new bar('arg1', 'arg2');
    console.log(obj.a1);
    console.log(obj.a2);
}

foo(Bar);


1
Use eval() if the string is cleaned of malicious code.
function foo ( bar ) { 
//code to check if bar is safe to use

//如果不是这两种情况,就清理它或返回; eval("thing . push ( new " + bar + "( arg1 , arg2 );");"); } 这应该可以工作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接