在已经定义的函数上Javascript“不是函数”错误

时间:2017-08-26 07:09:53

标签: javascript node.js function object graph-algorithm

我刚刚在节点中玩DFS,突然出现了这个错误。

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)

这是代码。 如果我引用该函数,它说“不是函数” 当我将该函数作为属性引用时,它表示“它是一个函数”

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]);

在recursiveDFS函数之外,一切都运行正常。

0 个答案:

没有答案