javascript apply on constructor, throwing “malformed formal parameter”

后端 未结 4 1229
星月不相逢
星月不相逢 2021-02-04 00:04

thanks to wonderful responses to this question I understand how to call javascript functions with varargs.

now I\'m looking to use apply with a constructor

4条回答
  •  悲哀的现实
    2021-02-04 00:41

    You can exploit the fact that you can chain constructors using apply(...) to achieve this, although this requires the creation of a proxy class. The construct() function below lets you do:

    var f1 = construct(Foo, [2, 3]);
    // which is more or less equivalent to
    var f2 = new Foo(2, 3);
    

    The construct() function:

    function construct(klass, args) {
    
      function F() {
        return klass.apply(this, arguments[0]); 
      }; 
    
      F.prototype = klass.prototype; 
    
      return new F(args);
    
    }
    

    Some sample code that uses it:

    function Foo(a, b) {
      this.a = a; this.b = b;
    }
    
    Foo.prototype.dump = function() {
      console.log("a = ", this.a);
      console.log("b = ", this.b);
    };
    
    var f = construct(Foo, [7, 9]);
    
    f.dump();
    

提交回复
热议问题