打字稿递归函数未定义

时间:2019-03-02 13:28:22

标签: javascript typescript recursion

对于打字稿/ javascript中的递归函数,我了解到“ this”上下文很棘手,因此我尝试使用箭头函数来避免上下文更改,但仍然无法正常工作。

代码如下所示:

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;
    }
}

要调用该函数,代码如下:

let model: BannerTreeModel = new BannerTreeModel();
model.rootItems = [{ label: 'item1', items: [{label: 'item2'}, {label: 'item3'}] }];
model.getMaxDepthSubtree(model.rootItems[0]);

在调试模式下,this中的this.getMaxDepthSubtree(child))未定义,因此此行中的 undefined function getMaxDepthSubtree 错误。有什么建议如何解决吗?

1 个答案:

答案 0 :(得分:0)

在forEach内部,this指的是全局window对象。

尝试将类上下文存储在变量_this中:

export class BannerTreeModel {
    rootItems: Item[] = [];
    var _this = this;

    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;
    }
}