0

I have the following JS class

class Tree {   

    constructor(rootNode) {
        this._rootNode = rootNode;
        rootNode.makeRoot();
    }
      
    getRoot() {
        return this._rootNode;
    }

    findNodeWithID(id) {
       return this.findNode(this._rootNode, id);
    }

    findNode = (node, id) => {
        if(node.id === id) {
            return node;
        } else {
            node.getChildren().forEach(child => {
                  this.findNode(child, id);
            });
        } 
        return null;
    }
}
    

I have two issues:

  1. This won't compile, gives an error

    findNode = (node, id) => { ^ SyntaxError: Unexpected token =

  2. When I change it to a regular function

findNode = (node, id) => {
       ...
    }

the method findNodeWithID doesn't work. Any idea why?

Asool
  • 13,031
  • 7
  • 35
  • 49

3 Answers3

3

its not yet part of the language , use babel

or

class Tree {   
  constructor(rootNode) {
    this._rootNode = rootNode;
    rootNode.makeRoot();

    // bind `this` in the constructor
    this.findNode = this.findNode.bind(this)
    this.findNodeWithID = this.findNodeWithID.bind(this)
    this.getRoot = this.getRoot.bind(this)
}

getRoot() {
    return this._rootNode;
}

findNodeWithID(id) {
   return this.findNode(this._rootNode, id);
}

findNode(node, id){
    if(node.id === id) {
        return node;
    } else {
        node.getChildren().forEach(child => {
              this.findNode(child, id);
        });
    } 
    return null;
  }
}
Ahmed Eid
  • 4,414
  • 3
  • 28
  • 34
1

In order to use arrow functions as class property you need to add transform-class-properties plugin as is explained here.

Julio Vásconez
  • 308
  • 5
  • 11
0

If you want findNode to be in the prototype of Tree, either use a regular function:

class Tree {
  …
  findNode(node, id) {
    …
  }
}

Or assign it directly to the prototype:

Tree.prototype.findNode = (node, id) => {…}

If you want findNode to be initialized as a property, do it in the constructor:

class Tree {
  constructor() {
    this.findNode = (node, id) => {…}
  }
  …
}

Or utilize TypeScript, which will allow the syntax you are using.

As you are referencing this in the function, you don’t want it to be an arrow function, as it will not have this context

Kit Isaev
  • 680
  • 8
  • 19