11

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.

1 Answer 1

18

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);
Sign up to request clarification or add additional context in comments.

4 Comments

You can also pass a thisArg as a second parameter. this isn't "context", it's a parameter of an execution context.
@RobG, thanks, I didn't know that. That's probably something new. I've edited the answer
It was introduced with forEach in ECMAScript ed 5. ;-)
@RobG, interesting, I must have missed it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.