javascript - TypeScript - 将一个对象的所有属性分配给另一个对象的简写方式
问题描述
我在 TypeScript 中有以下模式(但也只对 js 感兴趣)
const configs = {
"hello": {
x: 1,
y: 1,
z: 1
}
}
class Foo {
constructor(id) {
this.id = id;
const config = configs[id];
this.x = config.x;
this.y = config.y;
this.z = config.z;
}
}
const foo = new Foo("hello");
console.log(foo);
这有什么神奇的语法吗?我似乎记得有一种方法可以在 Python 中执行此操作(尽管我的谷歌搜索结果为空)
(编辑:为清楚起见,我想快速将 config 的所有属性分配为 Foo 的属性)
解决方案
你可以带上Object.assign
想要的东西。
const configs = {
"hello": {
x: 1,
y: 1,
z: 1
}
}
class Foo {
constructor(id) {
this.id = id;
Object.assign(this, configs[id]);
}
}
const foo = new Foo("hello");
console.log(foo);
推荐阅读
- python - Py2app如何创建一个真正的Standalone app?
- python - 如何在python中检查两列不同的csv文件?
- reactjs - react-native-firebase 不显示通知
- automotive - AGL 服务的简称是什么
- plc - PLC:将结构化文本 (ST) 转换为功能块图 (FBD)
- php - 未定义的索引:g-recaptcha-response 与 PHPMailer
- android - 在recyclerview中自动更改项目高度
- linux - 从两个程序中读取一个串行端口:Python 3
- java - 查找连通分量的有效算法
- c# - 将串行读取数据转换为 HEX 形式