Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda