When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as expected.
The code snippet is provided below:
export interface Item {
label: string;
items?: Item[];
}
export class BannerTreeModel {
rootItems: Item[] = [];
getMaxDepthSubtree(root_item: Item) {
let max_depth = 0;
if (root_item.items) {
root_item.items.forEach((child) => {
max_depth = Math.max(max_depth, this.getMaxDepthSubtree(child));
});
}
return ++max_depth;
}
}
To call this function, you can use the following code:
let model: BannerTreeModel = new BannerTreeModel();
model.rootItems = [{ label: 'item1', items: [{label: 'item2'}, {label: 'item3'}] }];
model.getMaxDepthSubtree(model.rootItems[0]);
During debugging, I noticed that this
within the line this.getMaxDepthSubtree(child))
was undefined, resulting in an error stating
. Can anyone offer suggestions on how to resolve this issue?undefined function getMaxDepthSubtree