javascript - 在不同的 TypeScript 类之间共享和改变对象
问题描述
我有以下打字稿代码:
class ClassA {
options: ClassOption;
B: ClassB;
constructor() {
this.B = new ClassB(this.options);
this.changeOptions();
}
changeOptions(): void {
const newOptions: ClassOption = new ClassOption("something");
this.options = newOptions;
}
}
class ClassB {
options: ClassOption;
constructor(opts: ClassOptions) {
this.options = opts;
}
someFunction(): ClassOption {
return this.options;
}
}
问题是当我实例化时ClassA
:
const a = new ClassA();
a.B.someFunction();
返回undefined
而不是从ClassA
'schangeOptions
方法设置的新选项。
解决方案
当在ClassA
's 构造函数中时,你会:
this.B = new ClassB(this.options);
this.options
仍然是undefined
,所以基本上在ClassB
你的构造函数中时:
this.options = opt;
您只是设置this.options
为undefined
而不是为其分配对ClassA
's的引用options
,因为它尚未初始化,所以它不存在。
即使您使用空对象进行初始化,如果您为其分配 ( options
)一个新值,也不会引用新值。ClassA
this.options = something
ClassB
你想要做的是:
用空对象初始化
ClassA
's :this.options
options: ClassOption = {};
将其传递给
ClassB
的构造函数。此处无需更改。调用时
ChangeOptions
,改变同一个对象,而不是用一个新对象替换它。您可以使用Object.assign
合并两个对象:changeOptions(): void { const newOptions: ClassOption = new ClassOption("something"); Object.assign(this.options, newOptions); // Note that after this, `this.options`' reference is preserved. }
在这里你可以看到它在纯 JavaScript 中工作:
class ClassA {
constructor() {
// 1. Initialise with an empty object:
this.options = {};
// 2. Pass that reference to ClassB instead of undefined:
this.B = new ClassB(this.options);
this.changeOptions();
}
changeOptions() {
// 3. Mutate this.options without changing its reference:
Object.assign(this.options, {
opt1: 1,
opt2: 2,
});
// 3. You can also do it like this:
this.options.opt3 = 3;
}
}
class ClassB {
constructor(options) {
this.options = options;
}
getOptions() {
return this.options;
}
}
const a = new ClassA();
a.changeOptions();
console.log(a.B.getOptions());
推荐阅读
- django - 如何将组权限分配给 Django 中的单个记录
- android - 有没有办法从firebaseauth获取名字和姓氏?
- list - 如何在lisp中对列表进行排序?
- kubernetes - 如何对 kubeadm 上的 metrics-server 进行故障排除?
- objective-c - 在 macOS 10.14 中使用 clang 编译 Objective-C?
- php - Symfony 文件夹中缺少帮助程序类
- bash - 如何将一系列关联数组的键设置为一个值
- python-3.x - 我希望在 on_raw_reaction 中为某个功能进行冷却
- r - 如何用 sapply 摆脱这个嵌套循环?
- python - 拒绝scrapy linkextractor中的某些链接