typescript - 构造一个新的可配置类
问题描述
我正在尝试创建可以具有默认值的可配置类,但如果需要,可以更改其配置。
这个想法是应该通过调用在 Test 类的静态属性中指定的类型来实例化类。
// Example
const app = Test.App // should return new instance of App class
另外,如果需要,我们应该配置它
// Example
const configured = Test.App.configure({...configuration}) // Should return new instance
主要问题是 App 构造函数只被调用一次,无论我调用多少次 Test.App - 它只是创建一个单例:(
如果需要 class App { public config: any;
constructor(a: string) {
console.log(this);
}
public configure(conf: any) {
this.config = conf;
return this;
}
}
class Test {
public static App = new App('App');
}
class Eval {
constructor() {
const a = Test.App.configure({test: true});
const b = Test.App;
console.log('Test', a, b);
}
}
解决方案
您可以使用 getter 在每次调用时创建一个新对象
class Test {
public static get App() {return new App('App')};
}
如果您调用Test.App
两次,它将是 2 个不同的对象,但是无法预测是否Test.App
会调用本身的configure
调用将跟随
推荐阅读
- android - 一次插入多个实体:房间
- ios - UI 元素在共享扩展 swift 中为零
- javascript - 通过脚本打开 PDF 文件、打印并关闭它
- dataframe - Apache Spark 中的“java.lang.OutOfMemoryError:Java 堆空间”错误?
- asp.net-core - Microsoft.Extensions.DependencyInjection 中的属性注入
- java - 有没有更短的方法来替换字符串中的一些字符而不是连续调用 String.replace ?
- python - 需要按 x 轴日期“期间”排序
- c# - 在 Revit 中关闭窗口 wpf
- java - 如何使用不支持 JOIN 关键字的 Oracle 8i 数据库在 JPA 中管理外键
- jquery - 如何在没有 flexbox 的 CSS 中构建锦标赛支架?