splat over JavaScript object (with new)?

前端 未结 2 922
感动是毒
感动是毒 2021-01-19 10:14

How do I splat across objects without using ECMA6 features?

Attempt

function can(arg0, arg1) {
    return arg0 + arg1;
}

function foo(bar, haz) {
           


        
2条回答
  •  终归单人心
    2021-01-19 11:04

    Using Object.create(proto) is the right way to go about this.

    Coco and LiveScript (Coffeescript subsets) offer a workaround:

    new foo ...args
    

    compiles to

    (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args), t;
      return (t = typeof result)  == "object" || t == "function" ? result || child : child;
      })
    (foo, args, function(){});
    

    And in CoffeeScript:

    (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(foo, args, function(){});
    

    These hacks are ugly, slow, and imperfect; for example, Date relies on its internal [[PrimitiveValue]]. See here.

提交回复
热议问题