2011-02-17 58 views

回答

19

您可以实例化一个变量参数列表这样的对象:

function instantiate(className, args) { 
    var o, f, c; 
    c = window[className]; // get reference to class constructor function 
    f = function(){}; // dummy function 
    f.prototype = c.prototype; // reference same prototype 
    o = new f(); // instantiate dummy function to copy prototype properties 
    c.apply(o, args); // call class constructor, supplying new object as context 
    o.constructor = c; // assign correct constructor (not f) 
    return o; 
} 

旁注:你可能希望通过直接引用类的构造函数:

var foo = instantiate(Array, [arg1, arg2, ...]); 
// Instead of: 
var foo = instantiate("Array", [arg1, arg2, ...]); 

...这使得这与非全局函数。

+0

感谢的人,这对我来说真是棒极了! – unjuken 2013-03-19 22:28:49

4

在ES5采用Object.create()

function instantiate(constructor, args) { 
    var instance = Object.create(constructor.prototype); 
    constructor.apply(instance, args); 
    return instance; 
} 

使用ES6的spread operator

var foo = new constructor(...args); 
+0

东西告诉我这将比接受的答案快四倍。 – 2015-09-05 06:31:09

-1

那么你总是可以做如下。任何添加到Dino原型中的东西都可以在实例化对象之间共享与普通构造器模式的区别在于,实例化对象不必具有完全相同的私有属性集。它们可以为它们中的每一个动态设置。

function Dino(a,b){ 
 
    for(i = 0; i< a.length; i++) this[a[i]] = b[i]; 
 
} 
 

 
var props = ["foo", "bar"], 
 
    values = [42, 37], 
 
     obj = new Dino(props,values); 
 
console.log(obj);