在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
Run Code Online (Sandbox Code Playgroud)
答案
从这里的回复中可以清楚地看出,没有内置的方式.apply()与new运营商通话.然而,人们提出了一些非常有趣的解决方案.
我首选的解决方案是Matthew Crumley的这个解决方案(我已将其修改为通过该arguments属性):
var createSomething = (function() {
function F(args) {
return Something.apply(this, args);
}
F.prototype = Something.prototype;
return function() {
return new F(arguments);
}
})();
Run Code Online (Sandbox Code Playgroud) 我如何概括下面的函数来取N个参数?(使用电话或申请?)
是否有一种编程方式将参数应用于"新"?我不希望构造函数被视为普通函数.
/**
* This higher level function takes a constructor and arguments
* and returns a function, which when called will return the
* lazily constructed value.
*
* All the arguments, except the first are pased to the constructor.
*
* @param {Function} constructor
*/
function conthunktor(Constructor) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
console.log(args);
if (args.length === 0) {
return new Constructor();
}
if (args.length === 1) {
return new Constructor(args[0]);
}
if (args.length === …Run Code Online (Sandbox Code Playgroud)