【问题标题】:Create instance without `new` operator with variable argument list使用变量参数列表创建没有`new`运算符的实例
【发布时间】:2013-06-12 10:33:36
【问题描述】:

我想创建一个 Point 的实例,带有和不带有 new 运算符,例如:

Point(5, 10); // returns { x: 5, y: 10 }
// or
new Point(5, 10); // also returns { x: 5, y: 10 }

到目前为止with the help of StackOverflow我已经成功了。

function Point() {
  if (!(this instanceof Point)) {
    var args = Array.prototype.slice.call(arguments);
    // bring in the context, needed for apply
    args.unshift(null);
    return new (Point.bind.apply(Point, args));
  }
  // determine X and Y values
  var pos = XY(Array.prototype.slice.call(arguments));
  this.x = pos.x;
  this.y = pos.y;
}

但这看起来很可怕,我什至将null 移到数组中,这样我就可以使用apply。就是感觉不对。

我找到了很多解决方案,如何使用新的构造函数和构造函数包装器来实现它,但我想让它尽可能简单(它只是一个简单、简单的点)。

有没有更简单的方法来实现这种行为?

【问题讨论】:

  • 这必须适用于所有功能还是仅适用于 1 个功能?如果只有 1,坦率地说,最好重写该函数。
  • @Qantas94Heavy 这只是Point 函数,我想表现得像这样。但当然它会被多次调用。

标签: javascript constructor arguments instance


【解决方案1】:

如果您不介意使用 ECMAScript 5 函数,Object.create() 可以提供帮助:

function Point()
{   var args = Array.prototype.slice.call(arguments);
    if (this instanceof Point) return Point.apply(null, args);
    var pos = XY(args); 
    var result = Object.create(Point.prototype);
    result.x = pos.x;
    result.y = pos.y;
    return result;
}

如果您需要 ECMAScript 3 兼容性,这个疯狂、复杂的解决方案是另一种解决方案(请注意,它只是 new Point 的内部等效项的包装器):

function Point() 
{   var pos = XY(Array.prototype.slice.call(arguments));
    function internalPoint()
    {   this.x = pos.x;
        this.y = pos.y;
    }
    internalPoint.prototype = Point.prototype;
    return new internalPoint;
}

【讨论】:

  • 就是这样。谢谢!很好的解决方案
  • 呃!我想我会使用 ECMAScript5。
  • @DanLee:请注意,IE8 及以下版本不支持第一种方法,除非您为Object.create() 添加 shim。话虽如此,我同意第二个很疯狂,但没有你做的那个疯狂:O.
  • 哈哈,是的,我们一起困惑 :) 我正试图了解这些结构。
猜你喜欢
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
相关资源
最近更新 更多