gpt4 book ai didi

javascript - 暴露 typescript 函数以调用 html 页面

转载 作者:行者123 更新时间:2023-11-28 03:02:33 27 4
gpt4 key购买 nike

我目前正在编写一个用 Parcel js 打包的 TypeScript 模块化库。应用程序将使用该库来实现特定功能。消费应用程序/网页将在其 html 中添加对我的库的引用,例如。

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

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

最佳答案

您可以使用服务/提供商概念。然而创建服务你需要单例对象。 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}

关于javascript - 暴露 typescript 函数以调用 html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60853451/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com