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

126
Visualizações
Main Getter for a Javascript class

So i want to create a class and add a getter to return something when getting the entire instance instead of a getter on one of the children.

example:

class Person {
  constructor(name){
    this.name = name
  }

  get () {
    return "My name is " + this.name;
  }
}

const Alexander = new Person("Alexander")

console.log(Alexander) // My name is Alexander

So the above is what i want to achieve, but i am unable to and struggling to find something online like this, unsure if it is possible or my wording is just incorrect.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The default toString() function of a class defines what should be printed if the class is converted to a string. You can override that function in the following way:

class Person {
  constructor(name){
    this.name = name;

    // override function here
    this.toString = function() {
      return "My name is " + this.name;
    }
  }
}

const Alexander = new Person("Alexander")
console.log("" + Alexander) // My name is Alexander

But it will only get printed if the object is converted to a string. For example by adding it to a string as in the example above (e.g. "" + object) or by doing String(object) or simply object.toString().

about 4 years ago · Santiago Trujillo 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