4

如何在不使用ECMA6 功能的情况下跨越对象?

试图

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

function foo(bar, haz) {
    this.bar = bar;
    this.haz = haz;
}

myArgs = [1,2];

can可以这样做:

can.apply(this, myArgs);

尝试使用时foo

new foo.apply(this, myArgs);

我收到此错误(因为我正在打电话new):

TypeError: function apply() { [native code] } is not a constructor
4

2 回答 2

4

使用Object.create

function foo(bar, haz) {
    this.bar = bar;
    this.haz = haz;
}

x = Object.create(foo.prototype);
myArgs = [5,6];
foo.apply(x, myArgs);

console.log(x.bar);
于 2015-01-25T01:33:19.640 回答
0

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.

于 2015-01-25T01:39:43.877 回答