【问题标题】:Spread class getter output to object将类 getter 输出传播到对象
【发布时间】:2019-05-03 14:58:55
【问题描述】:

给定一个类:

class Something {    
  constructor(something) {
   this._something = something; 
  }

  get something() {
    return this._something;
  }
}

我希望能够将访问器值传播到一个新对象中,例如:

const somethingObject = new Something(12);
const somethingSpread = { ...somethingObject };

但是,它只输出类的_something属性:

{ _something: 12 }

但我正在寻找的是这样的:

{ something: 12 }

我也尝试了Object.assign,它给出了与上面相同的输出:

const somethingAssigned = Object.assign({}, somethingObject);
// Output: { _something: 12 }

有可能做到这一点吗?

【问题讨论】:

标签: javascript class getter


【解决方案1】:

试试看:

class Something {
   private _something: Number;
   constructor(something: Number) {
     this._something = something;
   }

   public get something(): Number {
     return this._something;
   }

   public set something(value: Number) {
     this._something = value;
   }
}

function shallowClone(obj) {
   return Object.create(
   Object.getPrototypeOf(obj),
   Object.getOwnPropertyDescriptors(obj)
);

const var1 = new Something(12);
const var2 = shallowClone(var1);

console.log(var1, var1.something);
console.log(var2, var2.something);

输出:

某事 { _something: 12 } 12
某事 { _something: 12 } 12

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 2017-04-12
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多