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

时间:2020-01-08 02:14:35

标签: 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)
    }
    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文档(https://javascript.info/class),看来我的代码是用相同的方式建模的,但是似乎我缺少JS结构本身的基本知识。

在此处运行代码:https://repl.it/@JacksonEnnis1/My-Website

1 个答案:

答案 0 :(得分:1)

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

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

然后在35年发生错误时,this.nodes是字符串“ animals”,如果在JS中的字符串上迭代for in,则实例var将为您提供索引位置:因此为什么linkTo不是以“ 0”或任何后续对象闻名的方法。

相关问题