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
JS, how to access to "this" in a replacer function in a call to String.prototype.replace()

I have this piece of code:

class MyClass {
  constructor(text, pattern) {
    this.text = text;
    this.pattern = pattern;
  }

  run() {
    return this.text.replace(/(\d)/, this.replacer)
  }

  replacer(match, timeString, offset, string) {
    return this.pattern;
  }
}

It is a simplified example of my actual code.

When I run:

var v = new MyClass("text 1 2", "X");
v.run();

I see the error:

Uncaught TypeError: Cannot read properties of undefined (reading 'pattern')

How can access to this in this replacer function?

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

0

Use Function#bind to set the this value, or use an arrow function that calls this.replacer as the callback.

class MyClass {
  constructor(text, pattern) {
    this.text = text;
    this.pattern = pattern;
  }

  run() {
    return this.text.replace(/(\d)/, this.replacer.bind(this));
    // or return this.text.replace(/(\d)/, (...args) => this.replacer(...args));
  }

  replacer(match, timeString, offset, string) {
    return this.pattern;
  }
}
var v = new MyClass("text 1 2", "X")
console.log(v.run());

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