将 JavaScript new 关键字与可变长度参数数组一起使用
use the JavaScript new keyword with variable length arguments array
我正在构建一个函数,该函数允许对象由任何其他对象扩展
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
相关文章:
- 从node.js向CasperJS传递参数数组
- 如何从参数数组中调用回调
- 传递参数数组而不更改此项
- 在参数数组中传递整数数组
- 如何在JavaScript中获取字符串表示的参数数组
- 使用包含参数数组的数组调用函数,而不是仅列出数组
- JavaScript 修改 URL 参数数组
- 如何将参数数组传递给 JavaScript 中的另一个函数
- 传递参数数组
- 带有函数参数数组的闭包
- 将 JavaScript new 关键字与可变长度参数数组一起使用
- JavaScript:为什么更改参数变量会更改“参数”“数组”
- 如果使用参数数组调用,则日期会更改结果
- 试图理解Javascript中参数数组的概念
- Javascript:如何使用apply方法传递参数数组,然后在被调用的函数中访问它
- 发送单个参数与参数数组
- Array.from(arguments)是创建参数数组的一种可接受的方法
- 函数参数数组,如何影响reference =[]或reference.concat(array2)
- 在javascript中构建参数数组
- Javascript:是已弃用的参数数组