javascript - 如何将不同文件中的多个类包装成打字稿中的单个函数
问题描述
在尝试将多个类包装到一个函数中时,我遇到了打字稿构建的问题。
下面是示例代码。
// AppState.ts
export class AppState {
static id: string;
}
// AppLogic.ts
import { AppState } from './AppState'
export class AppLogic{
constructor(id : string){
AppState.id = id;
}
public getAppID() : string{
return AppState.id;
}
}
// main.ts
import { AppLogic } from './AppLogic';
export function AppwrapAPI(id : string): any{
class AppAPI{
private app : AppLogic;
constructor(id : string){
this.app = new AppLogic(id);
}
public getAppID() : string{
return this.app.getAppID();
}
}
return new AppAPI(id);
}
<!DOCTYPE html>
<html>
<head>
<title>Test app</title>
</head>
<body>
<script type="module">
import { AppwrapAPI } from "./dist/main.es.js";
let a1 = new AppwrapAPI("123");
alert(a1.getAppID()); ///"123"
let a2 = new AppwrapAPI("321"); ///"321"
alert(a2.getAppID());
alert(a1.getAppID()); ///"321" <<--- wrong data
</script>
</body>
</html>
上面的 ts 项目使用 rollup 生成如下 js 代码。
var AppState = /** @class */ (function () {
function AppState() {
}
return AppState;
}());var AppLogic = /** @class */ (function () {
function AppLogic(id) {
AppState.id = id;
}
AppLogic.prototype.getAppID = function () {
return AppState.id;
};
return AppLogic;
}());function AppwrapAPI(id) {
var AppAPI = /** @class */ (function () {
function AppAPI(id) {
this.app = new AppLogic(id);
}
AppAPI.prototype.getAppID = function () {
return this.app.getAppID();
};
return AppAPI;
}());
return new AppAPI(id);
}export{AppwrapAPI};//# sourceMappingURL=main.es.js.map
在此代码中,AppwrapAPI 函数仅包装 AppAPI 函数而不是所有函数,并且 AppState 函数位于 AppwrapAPI 函数之外,这在我为 AppwrapAPI 函数创建多个实例时会产生问题。
let a1 = new AppwrapAPI("123");
alert(a1.getAppID()); ///"123"
let a2 = new AppwrapAPI("321"); ///"321"
alert(a2.getAppID());
alert(a1.getAppID()); ///"321" <<--- wrong data
我想将所有三个类 AppState、AppLogic、AppAPI 包装在 AppwrapAPI 函数中,这样 AppState 就不会在多个实例之间共享。类似于下面的代码
"use strict";
function AppwrapAPI(id) {
class AppState {
}
class AppLogic {
constructor(id) {
AppState.id = id;
}
getAppID() {
return AppState.id;
}
}
class AppAPI {
constructor(id) {
this.app = new AppLogic(id);
}
getAppID() {
return this.app.getAppID();
}
}
return new AppAPI(id);
}
let a1 = AppwrapAPI("123");
console.log(a1.getAppID()); /// output : 123
let a2 = AppwrapAPI("321");
console.log(a2.getAppID()); /// output : 321
console.log(a1.getAppID()); /// output : 123
现在我手动修改生成的代码以避免这个问题,但是在使用从旧文件生成的源映射进行调试时,它给了我一些其他问题。
谁能向我建议如何修改打字稿代码以获得包装打字稿项目中所有类的单个函数?
解决方案
推荐阅读
- php - PHP回文挑战中的逻辑问题
- azure - 获取 - 操作返回错误:0:您未获得授权!使用 Azure 管道将 .nupkg 文件推送到 Orchestrator
- pine-script - 如何在斐波那契水平上进入/退出策略?
- python - 将 Tensorflow Keras 模型(编码器 - 解码器)保存为 SavedModel 格式
- python - 在 FOR 循环 python 中并行创建文件夹
- c++ - 如何比较两个函数的速度和性能
- spring-boot - 通过 zuul 对 eureka 客户端的请求被重定向到 Tomcat 主页
- python - Chudnovsky 算法返回一个负数和不正确的数字 - Python
- swift - if 语句中的随机结果
- grid - Powerbuilder 在网格数据窗口中添加的新列未在 Excel 中显示