angular - funciones recursivas en typescript/javascript
Estoy intentando llamar a la siguiente función recursivamente.
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;
};
cuando intenté llamar a la función mostraba un error "No se puede leer la propiedad 'getData' de undefined. ¿Hay algún error en el código o alguna otra manera de hacer esto?"
Respuesta #1
forEach acepta un callback, que es una función anónima, y this dentro de la función anónima se refiere a window en modo no estricto o a undefined en modo estricto.
Necesitas vincular el contexto:
Object.keys(value).forEach(function (keydata) {
let obj = value[keydata];
this.getData(keydata,value[keydata]);
console.log(key,obj,obj instanceof Object)
}.bind(this));
o usar una función flecha:
Object.keys(value).forEach((keydata) => {
let obj = value[keydata];
this.getData(keydata,value[keydata]);
console.log(key,obj,obj instanceof Object)
});
o simplemente pasar un puntero a this como segundo argumento a forEach:
Object.keys(value).forEach(function (keydata) {
let obj = value[keydata];
this.getData(keydata,value[keydata]);
console.log(key,obj,obj instanceof Object)
}, this);
