我需要从另一个函数中获取参数,该参数将用作创建新对象实例的构造函数名称:
function foo(bar) {
thing.push(new bar(arg1, arg2);
}
如何创建一个由字符串bar构造的新对象实例?
function foo(bar) {
thing.push(new bar(arg1, arg2);
}
如何创建一个由字符串bar构造的新对象实例?
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);
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 );");"); } 这应该可以工作