Javascript 无法从类内调用函数-无法识别函数

Javascript 无法从类内调用函数-无法识别函数,javascript,Javascript,我是JS的新手,我试图制作一个基本的节点图 class Node { constructor(name, nodes, data) { this.identity = name; this.nodes = nodes; this.data = data } linkTo(pnIdentity, childNode){ if(this.identity === pnIdentity){ this.nodes.push(childNode

我是JS的新手,我试图制作一个基本的节点图

class Node {
  constructor(name, nodes, data) {
    this.identity = name;
    this.nodes = nodes;
    this.data = data
    }

  linkTo(pnIdentity, childNode){
    if(this.identity === pnIdentity){
      this.nodes.push(childNode)
    }
    else{
      for(var node in this.nodes){
        console.log(node);
        if(node.identity === pnIdentity){
          node.nodes.push(childNode);
          break;
        }
        else{
          node.linkTo(pnIdentity, childNode);
        }
      }
    }
  }

  goTo(desired_id){
    for(var i in this.nodes){
      if(i.identity === desired_id){
        return i;
      }
    }
    return;
  }
}

let animals = new Node([], 'animals', []);
let cow = new Node([], 'cow', []);
let buffalo = new Node([], 'buffalo', []);

animals.linkTo('animals', cow);
animals.linkTo('cow', buffalo);

let nav = animals;
nav.goTo('cow');
nav.goTo('buffalo');
console.log(nav.identity);
我最初是用python编写的(因为我更熟悉它),并将其翻译成JS。 但是,当我运行它时,会出现以下错误:

TypeError: node.linkTo is not a function
    at Node.linkTo (/script.js:35:16)
    at /script.js:55:9
我查看了Js文档(),似乎我的代码是以同样的方式建模的,但是我似乎缺少了Js结构本身的一些基本内容

在此处运行代码:

您将“动物”节点声明为l51上的字符串“动物”:


然后在l35上,当错误发生时,
this.nodes
是一个字符串“animals”,如果您在JS中的字符串上迭代
for
,实例变量将给您一个索引位置:因此为什么
linkTo
不是一个已知的“0”方法或任何后续对象。

查看您的linkto else语句,其中它调用自身else内的方法{node.linkto(pnIdentity,childNode);}您在else语句中试图做什么?@EliaAhadi因此对于else语句,我将遍历每个子节点,检查它是否与父标识匹配。如果是,那么我希望它将我的新节点添加到该节点的子节点。
let animals = new Node([], 'animals', []);`