Javascript 如何将不同文件中的多个类包装到typescript中的单个函数中
在尝试将多个类包装到单个函数中时,我遇到了typescript构建的问题Javascript 如何将不同文件中的多个类包装到typescript中的单个函数中,javascript,typescript,ecmascript-6,typescript2.0,rollupjs,Javascript,Typescript,Ecmascript 6,Typescript2.0,Rollupjs,在尝试将多个类包装到单个函数中时,我遇到了typescript构建的问题 let a1 = new AppwrapAPI("123"); alert(a1.getAppID()); ///"123" let a2 = new AppwrapAPI("321"); ///"321" alert(a2.getAppID()); alert(a1.getAppI
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.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>
在这段代码中,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
现在我手动修改生成的代码以避免这个问题,但是在调试从旧文件生成的源映射时,它给了我一些其他问题
有谁能建议我如何修改typescript代码以获得封装typescript项目中所有类的单个函数吗?给定您的代码
AppState
只是一个静态id变量的全局容器。当然,它的变化将得到反映。有什么好的理由让它成为静态的吗?@Yoshi谢谢你的回复。这是我项目的一个示例代码,用于说明该用例。实际上,在我的项目中,AppState包含20多个对象,这些对象在不同的TS类文件中使用。AppState充当特定实例的全局存储。我将构建此项目,并在另一个项目中使用它,在该项目中,我要为此项目创建多个实例。当我创建多个实例时,我遇到了一个问题。我知道你想做什么,但我不明白为什么你会使用静态属性。根据它的定义,这就是。因此,如果需要实例,请相应地创建它们(例如,newappstate(…)
),并将其属性设置为实例的私有属性。
"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