最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angular - recursive functions in typescriptjavascript - Stack Overflow

programmeradmin8浏览0评论

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.

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.

Share Improve this question edited Apr 19, 2017 at 7:54 Max Koretskyi 106k67 gold badges353 silver badges515 bronze badges asked Apr 19, 2017 at 7:53 sravanthisravanthi 1751 gold badge2 silver badges15 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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);
发布评论

评论列表(0)

  1. 暂无评论