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

167
Vistas
recursive functions in typescript/javascript

I am trying to call the following function recursively.

 public  getData(key,value){

   this.htmlString += '<span style="color:cornflowerblue">'+key+' </span>:';

    if(value instanceof Object){
      Object.keys(value).forEach(function (keydata) {
        let obj = value[keydata];
        this.getData(keydata,value[keydata]);

        console.log(key,obj,obj instanceof Object)
      });
    }else{
      this.htmlString += '<span>'+value+'</span>';
    }
    return this.htmlString;
  };

when i tried to call teh function it was showing an error " Cannot read property 'getData' of undefined. Is there any wrong in the code or any other way to do this.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

forEach accepts a callback, which is an anonymous function, and this inside anonymous function refers to window in non-strict mode or undefined in strict mode.

You need to bind context:

  Object.keys(value).forEach(function (keydata) {
    let obj = value[keydata];
    this.getData(keydata,value[keydata]);

    console.log(key,obj,obj instanceof Object)
  }.bind(this));

or use an arrow function:

  Object.keys(value).forEach((keydata) => {
    let obj = value[keydata];
    this.getData(keydata,value[keydata]);

    console.log(key,obj,obj instanceof Object)
  });

or simply pass pointer to this as a second argument to forEach:

  Object.keys(value).forEach(function (keydata) {
    let obj = value[keydata];
    this.getData(keydata,value[keydata]);

    console.log(key,obj,obj instanceof Object)
  }, this);
about 4 years ago · Santiago Trujillo 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