Estoy tratando de 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 traté de 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 forma de hacerlo?
forEach acepta una devolución de llamada, que es una función anónima, y this función anónima interna se refiere a la window en modo no estricto o 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 use una función de flecha:
Object.keys(value).forEach((keydata) => { let obj = value[keydata]; this.getData(keydata,value[keydata]); console.log(key,obj,obj instanceof Object) }); o simplemente pase el puntero a this como un segundo argumento para forEach :
Object.keys(value).forEach(function (keydata) { let obj = value[keydata]; this.getData(keydata,value[keydata]); console.log(key,obj,obj instanceof Object) }, this);