Javascript ES6:来自foreach循环的递归函数调用失败

时间:2018-03-07 20:21:02

标签: javascript ecmascript-6

我是javascript的新手。

class ExpansionPath {
    expandPipelineNodes()
    {
        this.expandPipelineNode(this._rootNodes);
    }
    expandPipelineNode(node)
    {
        let bPipeline = false
        _.each(node.children,function(child){
            bPipeline |= this.expandPipelineNode(child);
        })

        ...
    }
}

当我调用函数expandPipelineNodes时,它调用expandPipelineNode(node),这很好。但当它进入foreach循环时,程序崩溃了。我调试了程序,它表明这在forEach循环中变为未定义。我还尝试了以下代码:

    node.children.forEach(function(child){
        bPipeline |= this.expandPipelineNode(child);
    })

但问题仍然存在。 我怎样才能在javascript中解决这个问题?

1 个答案:

答案 0 :(得分:2)

回调内的范围与外部范围不同。保留词法范围的简单方法是使用箭头函数:

_.each(node.children, (child) => {
    bPipeline |= this.expandPipelineNode(child);
})

您也可以使用Function.prototype.bind

_.each(node.children, function (child) {
    bPipeline |= this.expandPipelineNode(child);
}.bind(this))`

但这更详细。

有两种方法可以使它发挥作用,但它们在2018年并不酷。