动态修改JavaScript中的构造函数?
我想用Javascript中的构造函数做一些有点奇特的事情,但我不太确定如何做 我希望能够定义构造函数,然后将它们传递到另一个函数(“修改器”),如下所示:动态修改JavaScript中的构造函数?,javascript,function,constructor,arguments,abstraction,Javascript,Function,Constructor,Arguments,Abstraction,我想用Javascript中的构造函数做一些有点奇特的事情,但我不太确定如何做 我希望能够定义构造函数,然后将它们传递到另一个函数(“修改器”),如下所示: function OriginalConstructor() { // Do constructor things here // Like defining methods and properties } NewConstructor = modifyConstructor(OriginalConstructor);
function OriginalConstructor() {
// Do constructor things here
// Like defining methods and properties
}
NewConstructor = modifyConstructor(OriginalConstructor);
由此产生的“NewConstructor”在功能上应与此等效:
function NewConstructor(id, data) {
this.id = id;
this.data = data;
// Do stuff from the original constructor here
// i.e. the same methods and properties defined in the original constructor
}
有人知道如何创建“modifyConstructor”函数吗?您创建了一个按定义设置属性并调用原始构造函数的函数。例如:
function modifyConstructor(Constr) {
function NewConstructor(id, data) {
this.id = id;
this.data = data;
// Call original constructor
Constr.apply(this, Array.prototype.slice.call(arguments, 2));
}
// Setting the constructor property might not be a good idea depending on
// the use case
NewConstructor.prototype = Object.create(Constr.prototype, {
constructor: {value: NewConstructor, writable: true, configurable: true}
});
return NewConstructor;
}
这基本上实现了
NewConstructor
,作为Constr
的子类。您的示例看起来是一个糟糕的做法
这样更容易维护
我想这样说:
function OriginalConstructor(id, number){
this.id = id;
this.number = number;
}
var Obj = new OriginalConstructor();
function newConstructor(Obj){
this.id = Obj.id;
this.number = Obj.number * 2;
}
newObject = new newConstructor(Obj);
你从中得到的是:一个最初由原始构造函数创建的Obj,它的数据和状态从未改变,一个新对象是由modifiedConstructor创建的,它基于一个新构造函数修改一个对象。我不确定我是否得到了它,你想返回一个具有相同方法和原型的新构造函数,或者只返回所传递构造函数的新实例?听起来像是使用super()调用的经典子类化。或者他们应该共享同一个原型吗?另请参见它似乎应该是
newConstructor(Obj)代码>。但是您应该指出,newObject
没有任何其他Obj
可能具有的属性。因此,这与OP在他们的问题中描述的结果不同。修复了第一个问题,关于第二个问题,您认为新对象没有Obj可能具有的其他属性是什么意思,它是基于Obj持有的数据创建的。如果在OriginalConstructor.prototype
上设置了任何属性,newObject
没有它们。