【问题标题】:How to set multiple class properties to properties of one object如何将多个类属性设置为一个对象的属性
【发布时间】:2019-01-18 13:17:19
【问题描述】:

我面临的问题是我不想调用一个返回两个属性两次的函数,而是我基本上想这样做:

class xy {
   x: number;
   y: number;

   constructor (arg) {
       { this.x, this.y } = foo(arg); //this function returns an object with two properties
   }

}

而不是这个:

class xy {
   x: number;
   y: number;

   constructor (arg) {
       this.x = foo(arg).x;
       this.y = foo(arg).y;
   }
}

【问题讨论】:

  • Object.assign(this, foo(args) 这将分配foo 返回的所有属性,所以请注意它..

标签: javascript typescript class oop


【解决方案1】:

假设foo(arg) 返回一个只有xy 属性的对象:

class xy {
   x: number;
   y: number;

   constructor (arg) {
       Object.assign(this, foo(arg));
   }
}

如果foo 可能返回更多属性,您需要手动获取属性:

class xy {
   x: number;
   y: number;

   constructor (arg) {
       const {x, y} = foo(arg);
       Object.assign(this, {x, y});
   }
}

【讨论】:

    【解决方案2】:

    如前所述,您可以使用Object.assign,但要注意它会在foo 返回的对象中分配所有(自己的、可枚举的)属性.

    为避免这种情况,您可以使用解构:

    const {x, y} = foo(arg);
    this.x = x;
    this.y = y;
    

    它并没有给你带来太多,但是……

    您可以结合这些方法:

    const {x, y} = foo(arg);
    Object.assign(this, {x, y});
    

    ...以(理论上)临时对象分配为代价。 (我说“理论上”,因为 JavaScript 引擎可以优化它。但我不知道它会。)


    this proposal was put forward 就是针对这种情况的。可悲的是,它没有得到任何与委员会谈论的牵引力。如果该提案继续进行,您可以这样做:

    // NOT STANDARD JAVASCRIPT (the proposal hasn't even been accepted for Stage 0)
    this.{x, y} = foo(arg);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 2017-08-20
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      相关资源
      最近更新 更多