gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:08:25 29 4
gpt4 key购买 nike

我是 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

最佳答案

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

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

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

关于javascript - 无法从类内调用函数 - 函数无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59638527/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com