我有这门课:
export class ResourceFactory {
AlgoliaAppId = "AlgoliaAppId";
// ...
private resetParams() {
this.AlgoliaAppId = "AlgoliaAppId";
// ...
}
public initTemplate(objectName, directiveArgs): Template {
this.resetParams(); // <-- Can I, in any possible way, prevent this line from running?
this.AlgoliaAppId = `${this.AlgoliaAppId}${objectName}`;
// ... [long function content which I don't want to duplicate]
}
}
我正在尝试扩展 ResourceFactory
类:我想更改 AlgoliaAppId 名称并阻止 resetParams
运行。 (我无法编辑原始类)。
是否有任何方法可以覆盖 resetParams
,即使它是私有(private)的,或者至少以某种方式对 initTemplate 方法进行猴子修补,以便它不会运行行 this.resetParams
?
最佳答案
没有(干净的)方法可以从您无法控制的基类重写私有(private)
方法。我尝试了一些模块增强,看看是否可以将修饰符更改为 protected
但运气不佳; TypeScript 似乎希望所有重载都具有相同的修饰符。
但是,我能够在类声明之后修补原型(prototype)以破解重载,但代价是包含 @ts-expect-error
注释。似乎是与编译器战斗阻力最小的路径。下面是示例子类的样子:
class Example extends ResourceFactory {
AlgoliaAppId = "CustomName";
}
// @ts-expect-error
Example.prototype.resetParams = function resetParams() {
// your implementation
}
这是一个link to the playground也是如此。
关于javascript - 防止 TypeScript 公共(public)函数调用私有(private)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69654210/