繁体   English   中英

防止 TypeScript 公共函数调用私有函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM