2017-06-01 57 views
0

我需要從哪些將被用作構造函數的名稱爲對象的新實例另一個函數中的參數:的Javascript:使用變量作爲構造函數名稱

function foo(bar) { 
    thing.push(new bar(arg1, arg2); 
} 

我如何創建一個由bar的值構造的對象的新實例,其中bar是一個字符串?

+1

它會變成一個字符串嗎?爲什麼不把引用傳遞給構造函數呢? – Li357

回答

1

您可以傳遞構造函數。

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

0
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);」);} 這應該可以工作