在 Javascript 中将数组应用于"new"?



我想写下这样的函数:

function myNew(constructor) {
    return constructor.applyNew(Array.prototype.slice.call(arguments, 1));
}

不存在applyNew。有办法解决吗?

您首先必须创建一个从构造函数函数的原型继承的对象,然后将构造函数函数应用于该对象以初始化:

function applyNew(fn, args) {
    var obj;
    obj = Object.create(fn.prototype);
    fn.apply(obj, args);
    return obj;
}

编辑(我以前不考虑数组):

function myNew(constructor) {
    var args = arguments;
    function F() {
        return constructor.apply(this, Array.prototype.slice.call(args, 1));
    }
    F.prototype = constructor.prototype;
    return new F();
}

最新更新