【问题标题】:Exposing typescript function for consuming html page to call暴露用于使用 html 页面调用的 typescript 函数
【发布时间】:2020-07-06 06:30:08
【问题描述】:

我目前正在编写一个使用 parcel js 打包的 typescript 模块化库。该库将被应用程序用于特定功能。消费应用程序/网页将在其 html 中将引用添加到我的库中,例如。

<script defer src='mylib.js' />

我想在我的库中公开一个函数,供消费者调用和初始化我的库。公开这一功能的最佳方式是什么?

【问题讨论】:

    标签: javascript html typescript parceljs


    【解决方案1】:

    您可以使用服务/提供者的概念。但是创建服务需要单例对象。 JS很难做到。我已经阅读了几篇如何创建单例的文章。下面给出的样品可以满足你的要求。

    const singleton = clName => {
      return new Proxy(clName.prototype.constructor, {
        inst: null,
        construct: (target, args) => {
          if (!this.inst) this.inst = new target(...args);
          return this.inst;
        }
      });
    };
    class Util {
      constructor(configs) {
        this.time = +new Date();
        this.configs = configs;
      }
      printMsg() {
        console.log(this.msg);
      }
    }
    
    UtilClass = singleton(Util);
    
    const myObj = new UtilClass({ timeout: 100 });
    console.log(myObj)
    const myObj2 = new UtilClass({ timeout: 200 });
    console.log(myObj2)
    .as-console-wrapper { max-height: 100% !important; top: 0; color: blue; background: #fff}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多