Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
How can I get getter functions in javascript?

I'm trying to get getter functions in javascript instance.

Ideal(pseudo):

class T {
  internal values = a, b
  getters = c, d
}

const getters = []
for (key in test) {
  if (test[key] is getter)
    getters.push(test[key])
}
getters.forEach(getter => (getter.bind(test))()) // calls c() and d()

I thought Object.getOwnPropertyDescriptors can give me a getters, but it didn't work.

I saw the prototype(if I make instance via class) has getters, but I cannot access these values.

My code:

class Test {
  constructor() {
    this.a = 1;
    this.b = 2;
  }

  get c() { return this.a; }
  get d() { this.a + this.b; }
}

const test = new Test();

Object.getOwnPropertyDescriptors(test.__proto__);
/*
  Object { constructor: {…}, c: {…}, d: {…} }
   c: Object { get: c(), enumerable: false, configurable: true, … }
   constructor: Object { writable: true, enumerable: false, configurable: true, … }
   d: Object { get: d(), enumerable: false, configurable: true, … }
*/
test.__proto__.c; // undefined
test.__proto__.c(); // Uncaught TypeError: test.__proto__.c is not a function

There is c in prototype, but I can't access these values.

Is there any way to get these getters?

If link that I have to read exists, please notice me. Thank you.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to extract the get property from the descriptor and then use that - if you try to access the .c property directly, you'll be invoking the getter (or setter).

class Test {
  constructor() {
    this.a = 1;
    this.b = 2;
  }

  get c() { return this.a; }
  get d() { this.a + this.b; }
}

const test = new Test();
const testGetters = Object.values(Object.getOwnPropertyDescriptors(Object.getPrototypeOf(test)))
  .filter(descriptor => descriptor.get)
  .map(descriptor => descriptor.get);
console.log(testGetters);
console.log('Invoking getter manually:', testGetters[0].call(test));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda