【发布时间】:2012-04-03 13:24:10
【问题描述】:
我正在尝试创建一个函数,该函数将接受参数arg1, arg2...,然后将它们传递给新对象 C 的构造函数,如下所示:new C(arg1, arg2...),因此要创建 C 的新实例,用户只需拥有打电话给C(arg) 而不是new C(arg)。这是我的第一次尝试:
var C = function(a){ this.a = a; }
var Cn = function(){
new C.apply(this, arguments);
}
Cn(0) // Should make a new C with a property a equal to 0
new C(0) // ie the same as this
编辑:注意,我需要它接受任意数量的参数,而不是使用 eval。我正在创建一个在 js 中实现 Algebraic Data Types 的库。
编辑:解决方案是采用 Jeremy's Idea 并对其进行调整以采用无限数量的参数:
var C = function() {
// A unique object so we can identify when we used the 'newless' constructor
var newlessConstructorObj = {}
// Check to see if C has been called with `new`
if(!(this instanceof C))
// If not pass arguments as single arg back to C
return new C(newlessConstructorObj, arguments);
// Check to see if we got here from the line above, if so the arguments were passed in the second arg
var args = (arguments[0] === newlessConstructorObj) ? arguments[1] : arguments
// Do stuff with args
this.a = args[0];
}
C(0);
new C(0);
【问题讨论】:
标签: javascript object prototype