Use of .apply() with 'new' operator. Is this possible?

后端 未结 30 2778
Happy的楠姐
Happy的楠姐 2020-11-22 00:39

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible?

30条回答
  •  自闭症患者
    2020-11-22 01:16

    @Matthew I think it's better to fix the constructor property also.

    // Invoke new operator with arbitrary arguments
    // Holy Grail pattern
    function invoke(constructor, args) {
        var f;
        function F() {
            // constructor returns **this**
            return constructor.apply(this, args);
        }
        F.prototype = constructor.prototype;
        f = new F();
        f.constructor = constructor;
        return f;
    }
    

提交回复
热议问题