【发布时间】:2010-12-09 01:44:33
【问题描述】:
在 JavaScript 中,我想创建一个对象实例(通过 new 运算符),但将任意数量的参数传递给构造函数。这可能吗?
我想做的是这样的(但下面的代码不起作用):
function Something(){
// init stuff
}
function createSomething(){
return new Something.apply(null, arguments);
}
var s = createSomething(a,b,c); // 's' is an instance of Something
答案
从这里的响应中可以清楚地看出,没有内置方法可以使用 new 运算符调用 .apply()。然而,人们提出了一些非常有趣的解决方案来解决这个问题。
我首选的解决方案是this one from Matthew Crumley(我已对其进行了修改以传递arguments 属性):
var createSomething = (function() {
function F(args) {
return Something.apply(this, args);
}
F.prototype = Something.prototype;
return function() {
return new F(arguments);
}
})();
【问题讨论】:
-
[Matthew Crumley 的解决方案][1] 在 CoffeeScript 中:construct = (constructor, args) -> F = -> constructor.apply this,args F.prototype = constructor.prototype new F createSomething = ( ()-> F = (args) -> Something.apply this.args F.prototype = Something.prototype return -> new Something 参数)() [1]: stackoverflow.com/questions/1606797/…
-
我认为这个线程的要点是
new做了两件事:(i) 设置原型,(ii) 将this设置为所述对象/原型的构造函数应用组合。您可以使用Object.create()来实现这一点,也可以通过对Object.create()采取自己的看法并使用闭包捕获上下文。 -
我通过将类作为参数传递给外部函数来概括它。所以这基本上是一个工厂工厂。
-
@Pumbaa80 的答案似乎是更好的解决方案,ES6 Traceur 也使用它来填充
spread运算符。 =) 在 Chrome 中它也快一点:jsperf.com/dynamic-arguments-to-the-constructor -
谁能解释一下为什么这家伙不能像
var s = new Something(a,b,c)那样做?我无法得到它:/
标签: javascript oop class inheritance constructor