【问题标题】:How can I use the spread operator with 'this'?如何将扩展运算符与“this”一起使用?
【发布时间】:2019-01-17 06:01:17
【问题描述】:

我在 TypeScript 中定义一个类。 因此,使用扩展运算符我可以发出这样的问题:

class Foo {
  constructor(data: IDataStructure){
      const { ...k } = data; // and then k has taken over all the properties of data. Great!
  }

  public render () {

    return(<div/>

   );
  }
}

现在,我想做同样的事情,但不是将属性放在k 中,而是放在正在创建的当前对象中。 IE。我想做类似const { ...this } = data; 这样的事情在 Typescript 中有什么聪明的方法吗?

【问题讨论】:

  • ... 不是(也不能是)操作员。这只是主要语法。

标签: node.js typescript spread-syntax


【解决方案1】:

您不能使用展开向现有 对象添加属性。目前没有 syntax 方法可以做到这一点;相反,使用Object.assign:

Object.assign(this, data);

示例(在 JavaScript 中)

class Example {
    constructor(data) {
        Object.assign(this, data);
    }
}
const e = new Example({answer: 42});
console.log(e.answer); // 42

注意Object.assign 做了属性的浅拷贝。因此,如果data 的属性之一引用了一个对象,那么reference 会被复制过来,datathis 都将引用同一个对象:

const data = {
    answer: 67,
    obj: {
        prop: "value"
    }
};
Object.assign(this, data);
console.log(this.obj === data.obj); // true, it's a shallow copy, they both refer
                                    // to the same object

如果您需要深度副本,其中复制data 也会复制data.obj,请参阅this question's answers

【讨论】:

  • 我刚刚发现它并没有真正起作用。它实际上是把你的课搞砸了。从那时起,每当您想通过“this”访问类的变量时,它都被搞砸了,因为“this”现在指向数据。
  • @Jose - 不,不是。 this 拥有 data 上内容的浅拷贝。我已在答案中添加了有关深度克隆的注释,但您的问题中没有任何内容表明您需要深度副本。
猜你喜欢
  • 2020-10-21
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-29
  • 2016-06-28
  • 2011-01-28
相关资源
最近更新 更多