[英]Prevent TypeScript public function calling a private function
我有这门课:
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
即使它是私有的,或者至少以某种方式对 initTemplate 方法进行猴子补丁,这样它就不会运行this.resetParams
行?
您可以将resetParams
方法的可见性从private
更改为protected
,然后从基类覆盖它:
export class ResourceFactory {
AlgoliaAppId = "AlgoliaAppId";
protected resetParams() { /* default implementation */ }
public initTemplate(objectName, directiveArgs): Template { /* ... */ }
}
class Example extends ResourceFactory {
AlgoliaAppId = "CustomeName";
protected resetParams() { return; } // Override here
}
确保在超类和子类中将该方法标记为protected
,以确保它不能从外部 API 调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.