[英]recursive functions in typescript/javascript
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'。代码中是否有任何错误或任何其他方法来执行此操作。
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
: 或者只是将指针作为forEach
的第二个参数传递给this
:
Object.keys(value).forEach(function (keydata) {
let obj = value[keydata];
this.getData(keydata,value[keydata]);
console.log(key,obj,obj instanceof Object)
}, this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.