动态修改构造函数在JavaScript中? [英] Dynamically modifying Constructors in JavaScript?
问题描述
我在找做一些有点奇特在JavaScript中构造函数,我不太清楚如何做到这一点。
I'm looking to do something a little bit fancy with constructor functions in Javascript, and I'm not quite sure how to do it.
我希望能够像这样定义构造函数,然后将它们传递到另一个函数(一个修改器):
I want to be able to define Constructor functions, and then pass them into another function (a "modifer") like this:
function OriginalConstructor() {
// Do constructor things here
// Like defining methods and properties
}
NewConstructor = modifyConstructor(OriginalConstructor);
和由此产生的NewConstructor应该是功能上等同于这样的:
And the resulting "NewConstructor" should be functionally equivalent to this:
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功能?
Does anybody know how to go about creating the "modifyConstructor" function?
推荐答案
您创建为您定义并调用原来的构造函数设置属性的功能。例如:
You create a function that sets the properties as you defined and calls the original constructor. For example:
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
作为一个子类,无论构造方法
是
This basically implements NewConstructor
as a subclass of whatever Constr
is.
这篇关于动态修改构造函数在JavaScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!