我想用 Javascript 中的构造函数做一些有点花哨的事情,但我不太确定该怎么做。
我希望能够定义构造函数,然后将它们传递给另一个函数(“修饰符”),如下所示:
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
的子类。
关于javascript - 动态修改 JavaScript 中的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25451269/