typescript/javascript 中的递归函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43489704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:27:57  来源:igfitidea点击:

recursive functions in typescript/javascript

javascriptangulartypescriptrecursion

提问by sravanthi

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.

当我尝试调用 teh 函数时,它显示错误“无法读取未定义的属性 'getData'。代码中是否有任何错误或以任何其他方式执行此操作。

回答by Max Koretskyi

forEachaccepts a callback, which is an anonymous function, and thisinside anonymous function refers to windowin non-strict mode or undefinedin strict mode.

forEach接受一个回调,它是一个匿名函数,匿名函数this内部是指window非严格模式或undefined严格模式。

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 thisas a second argument to forEach:

或者简单地将指针this作为第二个参数传递给forEach

  Object.keys(value).forEach(function (keydata) {
    let obj = value[keydata];
    this.getData(keydata,value[keydata]);

    console.log(key,obj,obj instanceof Object)
  }, this);