将arguments数组传递给构造函数

时间:2013-12-26 17:55:46

标签: javascript

我正在为我的类构造函数使用以下模式:

function SomeConstructor(a){
    if (!(this instanceof arguments.callee)){
        return new arguments.callee(a);
    }
    //the constructor properties and methods here
}

当我知道我传递给构造函数的参数数量时,这很有效。问题在于,在某些情况下,在使用继承时,我没有,例如:

SomeConstructor.prototype = AnotherClass();

这并不像查找AnotherClass的定义那么简单,因为这个逻辑是框架的一部分并自动生成。我尝试通过调用apply上的arguments.callee方法解决此问题,但收到以下错误:

function apply() { [native code] } is not a constructor

直接将参数传递给callee将不起作用,因为它是一个数组。是否有与apply类似的东西与构造函数或我在这里看不到的解决方法一起使用?

此外,这是一个内部框架,所以我可以调整构造函数生成的内容,唯一的要求是:

  • 我们必须能够在不使用外部new关键字的情况下实例化类
  • 类必须是可继承的,这样子构造函数可能不知道(在编译时)父接收的所有参数
  • 类初始化必须是Class(a, b, c)格式,我不能将参数包装在数组

修改 我尝试应用序列的代码如下所示:

function SomeConstructor(){
    if (!(this instanceof arguments.callee)){
        return new arguments.callee.apply(arguments);
    }
    //the constructor properties and methods here
}

0 个答案:

没有答案