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

157
Visualizações
How I can convert class instance to string when using new?

I need to achieve the following behavior: So when creating a class instance via new, I received a string, not a class object. How to implement this? Is it even possible?

For example

class ExampleClass{
  constructor(str) {
    this.str = str;
  }
     // some code I guess...
}

const str = new ExampleClass('example')

console.log(str) // 'example'
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Give this a try:

class ExampleClass extends String {}
about 4 years ago · Juan Pablo Isaza Relatório

0

While using Class with new it create this instance internally and return it

HOW IT WORK INTERNALLY

let ExampleClass = function(_str){
  //this = Object.create(ExampleClass.prototype);
  this.str = _str
  // return this;
}
str = new ExampleClass('EXAMPLE');

Good practice: Can create helper function or getters instead of changing implementation

class ExampleClass{
  constructor(str) {
    this._str = str;
  }
  // some code...
  get str(){return this._str;}
  set str(str){this._str = str;}
  helperFetchStr(){ return this._str;}
}
new ExampleClass('EXAMPLE1').str;
new ExampleClass('EXAMPLE2').helperFetchStr();

Extending the String class. Here prototype will be from string enabling you to perform all string operations directly on str

let similar = new String("EXAMPLE")

class ExampleClass extends String {
  constructor(str) {
    super(str);
  }
  // some code...
}
const str = new ExampleClass('EXAMPLE');
//console.log(str.{STRING_OPERATIONS})
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