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
recursive functions in typescript/javascript
提问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
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.
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 this
as 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);