Jackson Ennis
Jackson Ennis

Reputation: 19

Unable to call function from within class - Function not recognized

I'm a novice at JS and I was trying to make a basic node graph.

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

I wrote this originally in python (because I'm more familiar with it) and translated it into JS. However, when I run it, I get this error:

TypeError: node.linkTo is not a function
    at Node.linkTo (/script.js:35:16)
    at /script.js:55:9

I looked at the Js documentation (https://javascript.info/class) and it appears that my code is modeled the same way, however it seems like I am missing something fundamental with the way JS structures itself.

Run code here: https://repl.it/@JacksonEnnis1/My-Website

Upvotes: 0

Views: 51

Answers (1)

Andre Figueiredo
Andre Figueiredo

Reputation: 13425

you declaring your "animal" nodes, as string "animals" on l51:

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

then on l35, when the error occurs, this.nodes is a string "animals", and if you iterate for in over a string in JS, the instance var will give you an index position: hence why linkTo is not a method known for "0" or any subsequent object.

Upvotes: 1

Related Questions