将一个对象的所有属性分配给另一个对象的快捷方式

2024-09-27 19:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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中有一种方法可以做到这一点(尽管我的google搜索结果是空的)

(编辑:为了清楚起见,我想快速将config的所有属性指定为Foo的属性)


Tags: idconfighello属性foojs模式this
1条回答
网友
1楼 · 发布于 2024-09-27 19:30:15

您可以将^{}与想要的对象一起使用

&13; 第13部分,;
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);
和#13;
和#13;

相关问题 更多 >

    热门问题