Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  153] [ 2]  / answers: 1 / hits: 19602  / 7 Years ago, wed, april 19, 2017, 12:00:00

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.


More From » angular

 Answers
23

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);

[#58097] Monday, April 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devane

Total Points: 451
Total Questions: 88
Total Answers: 100

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;