【问题标题】:Get all getters results as class variables without specific invoking无需特定调用即可将所有 getter 结果作为类变量获取
【发布时间】:2022-01-22 12:10:45
【问题描述】:

有没有一种方法可以在没有特定调用的情况下获得实例上的所有 getter 结果? 我想通过循环类成员将所有类获取器作为类的简单成员。

我有这样的课:

export class Test {
  constructor() {}

  get foo() {
    return 1
  }

  get bar() {
    return 2
  }
}

用途是创建一个新实例:const test = new Test()

有没有一种方法可以让所有的 getter 作为简单的类变量成员而不是函数?所以我可以将对象从服务器传递到客户端。

谢谢!

【问题讨论】:

  • 很难说你在问什么或者你遇到了问题。您可以自己调用吸气剂。你应该更多地解释你在做什么,你正在将数据发送到服务器。您还可以实现 toJson 方法以与 JSON.stringify 一起使用请参阅stackoverflow.com/a/42107611/227299
  • “没有特定调用”是什么意思?如果不调用 getter 结果,您将无法获得它们。
  • @JuanMendes "做 HR 之家"???
  • @Bergi 对不起,来自电话????

标签: javascript class getter member


【解决方案1】:

class Test {
  constructor() {}

  get foo() {
     return 1
  }

  get bar() {
    return 2
  }
}

const allGetterKeys = Object.entries(Object.getOwnPropertyDescriptors(Test.prototype)).filter(([key, descriptor]) => typeof descriptor.get === 'function').map(([key]) => key);

const test = new Test();
const out = {};

for(const key of allGetterKeys)
{
  out[key] = test[key];
}

console.log(out);

第一行来自this answer(它获取类中所有getter的键名)。然后 for 循环使用所有这些键从 getter 获取输出并将它们放入一个普通对象 out。该对象只是键值对。

【讨论】:

    猜你喜欢
    • 2015-05-10
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多