0

I was just playing around with DFS in node, and suddenly got this error.

TypeError: sNode.hasNeighbors is not a function
    at recursiveDFS (/home/***/Graphs/dfs2.js:53:27)
    at /home/***/Graphs/dfs2.js:56:17
    at Array.forEach (<anonymous>)
    at recursiveDFS (/home/***/Graphs/dfs2.js:54:30)
    at Object.<anonymous> (/home/***Graphs/dfs2.js:62:1)

Here is the code. If I reference the function it says "is not a function" When I reference the function as a property it says "it's a function"

function Node(vert) {
    this.visited = false;
    this.vertex = vert;
    let neighbors = [];

    this.addNeighbors = function(node_str) {
        if (node_str.length == 1) {
            neighbors.push(parseInt(node_str));
        } else {
            nodes = node_str.split(" ");
            for (var i = 0; i < nodes.length; i++) {
                neighbors.push(parseInt(nodes[nodes[i]]));
            }
        }
    };

    this.hasNeighbors = function() {
        return neighbors.length > 0;
    };

    this.getNeighbors = function() {
        return neighbors;
    };
}

let node = [];
node[0] = new Node(0);
node[1] = new Node(1);
node[2] = new Node(2);
node[3] = new Node(3);
node[4] = new Node(4);
node[5] = new Node(5);
node[6] = new Node(6);
node[7] = new Node(7);
node[8] = new Node(8);
node[9] = new Node(9);

node[0].addNeighbors("1");

node[1].addNeighbors("0 1");

node[2].addNeighbors("1 3");

node[3].addNeighbors("2 4 5");

node[4].addNeighbors("3 5 6");

function recursiveDFS(sNode) {
    if (!sNode.visited) {
        sNode.visited = true;
        //console.log(sNode.hasNeighbors());
        sNode.getNeighbors().forEach(function(neighbor) {
            if (!neighbor.visited) {
                recursiveDFS(neighbor);
            }
        }, this);
    }
}

recursiveDFS(node[0]);

Outside the recursiveDFS function everything works completely fine.

  • 2
    `.getNeighbors()` returns an array of numbers, hence `neighbor` is a number. And a number has no `.hasNeighbors()` or `.getNeighbors()` method. – Andreas Aug 26 '17 at 07:14
  • oh holy crap am I an idiot thank you – Viktor Velev Aug 26 '17 at 07:18
  • You also might want to use prototype to create functions on `Node`. For more info see https://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript – Marco de Zeeuw Aug 26 '17 at 08:02

0 Answers0