0

I am new to javascript.

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

        ...
    }
}

When I call the function expandPipelineNodes, it calls expandPipelineNode(node) which is fine. But when it goes inside the foreach loop, the program crashes. I have debugged the program and it showed that this becomes to undefined in the forEach loop. I also tried the following code:

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

But the problem remains. How can I solve this problem in javascript?

Code Pope
  • 5,075
  • 8
  • 26
  • 68

1 Answers1

2

The scope inside callback is different to the scope outside. Simple way to preserve lexical scope is to use arrow function:

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

You could also use Function.prototype.bind:

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

but this is more verbose.

There are couple of more ways to make it work but they are not cool in 2018.

dfsq
  • 191,768
  • 25
  • 236
  • 258