修改类的构造函数



我已经有一个修改其他类方法的函数:

class MyClass {
constructor() {
this.num = 1;
}
inc(){
this.num++;
}
}
runAfterMethod(classHandle, methodName, executeAfter) {
const oldHandle = classHandle.prototype[methodName];
classHandle.prototype[methodName] = function () {
const returnValue = oldHandle.apply(this, arguments);
//@ts-ignore
executeAfter.apply(this, arguments);
return returnValue;
};
}
runAfterMethod(MyClass, "inc", function() {console.log(this.num)})
new MyClass().inc(); // Prints 2

但是,这不适用于类的构造函数(因为它在技术上是类本身)

我真正满意的是模仿这种行为的东西:

class MyClass {
constructor() {
this.num = 1;
}
}
extendConstructor(MyClass, function(){
this.str = "hello world"
})
new MyClass(); // num: 1, str: "hello world"

我已经看过诸如如何修改 ES6 类的构造函数之类的东西,但是,它们都需要=某处,这在函数内部不起作用(其中仅更改函数内类的值,而不是类本身)

改变现有类真的很奇怪。IMO 的代码气味要少得多的是围绕实例化类的类创建一个包装器,然后使用自定义回调调用它,然后返回实例 - 它会简单得多。这对你的目的有用吗?

class MyClass {
constructor() {
this.num = 1;
}
}
const extendConstructor = (theClass, callback) => function(...args) {
const instance = new theClass(...args);
callback.call(instance);
return instance;
};
const Extended = extendConstructor(MyClass, function(){
this.str = "hello world"
})
console.log(new Extended()); // num: 1, str: "hello world"

最新更新