簡體   English   中英

摔倒JavaScript對象(帶有新對象)?

[英]splat over JavaScript object (with new)?

如何在不使用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

使用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);

使用Object.create(proto)是解決此問題的正確方法。

Coco和LiveScript(Coffeescript子集)提供了一種解決方法:

new foo ...args

編譯為

(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(){});

在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(){});

這些駭客是丑陋的,緩慢的,不完善的。 例如, Date依靠其內部的[[PrimitiveValue]] 這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM