我正在构建一个允许对象被任何其他对象扩展的函数
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:
new constructor(args)
父对象的构造函数接收参数,参数是参数对象或数组。
我想要的是能够打电话
new constructor.apply(args)
或类似的东西,我不是要更改这个新的上下文,apply 是我知道的使用 args 对象或数组调用方法的唯一方法。
感谢您的帮助:)
更新,我找到了更好的方法
这是我想出的一个更好的继承方法,它避免使用贬值的 proto
与我发现的其他继承方案相比,此方法有几个优点。最大的是它不合并原链的多个级别。许多方案将子类的原型(prototype)方法与父类实例变量混合在一起,或者更糟的是,将父类初始化的所有方法和属性直接放入子类的主体中。
缺点是,它是单继承,不能更改单个实例的继承,因为原型(prototype)属性属于构造函数。
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__
已弃用。
关于javascript - 使用带有可变长度参数数组的 JavaScript new 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677962/