Dynamic instantiation in JavaScript

前端 未结 3 1004
情歌与酒
情歌与酒 2020-12-15 22:54

Apart from eval, is there any other way to instantiate an object using variable argument list?

E.g.: var foo = instantiate(className, [arg1, arg2, ...])

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 23:20

    You can instantiate an object with a variable argument list like this:

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

    Side note: you may wish to pass a direct reference to the class constructor function:

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

    ... which makes this compatible with non-global functions.

提交回复
热议问题