0

I'm having some issue with the js strange scope behaviour. I have this Graph function (a simple wrapper of https://github.com/cpettitt/graphlib). If I add nodes one by one like I do with the node labeled "1" all works, if I use a forEach I have a scope problem.

function Graph() {
    this.g = new graphlib.Graph();
    this.setNode = function (id, value) {
        this.g.setNode(id, value || {}); 
    }
}

var gg = new Graph();
    gg.setNode("1"); //works

    ["2a","2b"].forEach(gg.setNode); //doesn't work

The error is Cannot read property 'g' of undefined the g instance var of Graph isn't visible in that forEach.

alfredopacino
  • 2,979
  • 9
  • 42
  • 68
  • No, the error means that `this` is `undefined` (you are trying to access the property `g` on `this` (`this.g`), "Cannot read property 'g' of undefined" therefore means that `this` is `undefined`). While `this` and "scope" are related, the problem is with `this`, not the scope. – Felix Kling Jan 14 '17 at 23:16

1 Answers1

0

Use the second argument to forEach to lock the function call to a scope:

["2a","2b"].forEach(gg.setNode, gg);
Ates Goral
  • 137,716
  • 26
  • 137
  • 190