将 JavaScript new 关键字与可变长度参数数组一起使用

use the JavaScript new keyword with variable length arguments array

本文关键字:参数 数组 一起 new JavaScript 关键字      更新时间:2023-09-26

我正在构建一个函数,该函数允许对象由任何其他对象扩展

Object.prototype.extend = function(constructor, args) {
    var proto = this;
    while(proto.__proto__.constructor !== Object) {
        proto = proto.__proto__
    }
    proto.__proto__ = new constructor(args)
    console.log(this); 
}

该方法将像这样调用:

function ChildModelConstructor(1,2,3) {
    this.extend(ParentModel, arguments)
}
or
instanceOfChildModel.extend(ParentModel, [1,2,3])

问题是如果我像这样称呼新:

new constructor(args)

父对象的构造函数接收参数,该参数是参数对象或数组。

我想要的是能够打电话

new constructor.apply(args)

或类似的东西,我并没有试图改变这个新的上下文,应用是使用 args 对象或我知道的数组调用方法的唯一方法。

感谢您的帮助:)

更新,我找到了更好的方法

这是我想出的更好的继承方法,它避免使用折旧的原型

与我发现的其他继承方案相比,这种方法有几个优点。 最大的问题是它不会合并原型链的多个级别。 许多方案将 childClass 的原型方法与父类实例变量混合在一起,或者更糟糕的是,父类的所有方法和属性都直接初始化到 childClass 的主体中。

缺点是,它是单个继承,并且您无法更改单个实例的继承,因为原型属性属于构造函数。

Function.prototype.inherit = function(parentClass) {
    var newPrototype = Object.create(Object.create(parentClass.prototype));
    for(key in this.prototype){
        newPrototype[key] = this.prototype[key];
    }
    this.prototype = newPrototype;    
    this.prototype.constructor = this;
    this.prototype.parentClass = parentClass;
    this.prototype.initParent = function(args) {
        var proto = Object.getPrototypeOf(Object.getPrototypeOf(this))
        this.parentClass.apply(proto, args);
    }
    this.prototype.uber = function() {
        return Object.getPrototypeOf(Object.getPrototypeOf(this));
    }        
}

您可以像这样设置继承:

function Model(n) {
    this.initParent(arguments)
    this.test = n*2;
}
Model.inherit(BaseClass);

下面是 JSFiddle http://jsfiddle.net/michaelghayes/2rHgK/中稍微详细的版本

这是未经测试的,但我认为它会起作用。取代:

proto.__proto__ = new constructor(args)

跟:

proto.__proto__ = {};
proto.__proto__.prototype = constructor.prototype;
constructor.apply(proto.__proto__, args);

请注意,__proto__已被弃用。

最好不要将东西附加到对象原型,而只需手动设置继承:

Model function() {
  //init parent first because of chromes hidden classes
  ParentClass.apply(this, [].slice.call(arguments))
  //new instance properties
  this.something = 'something'
}
Model.prototype = Object.create(ParentClass.prototype, {
  constructor: {value: Model}
})
//Prototype props
Model.prototype.whatever = function(){return 'whatever'}

这也允许您在启动父类之前修改 args,因为您的新类不应仅限于使用与其父类完全相同的 args