ES6箭头函数,语法错误

时间:2018-01-05 15:25:39

标签: javascript ecmascript-6 es6-class arrow-functions

我有以下JS类

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

我有两个问题:

  1. 这不会编译,会出错

    findNode =(node,id)=> {              ^ SyntaxError:意外的令牌=

  2. 当我将其更改为常规功能时

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

    方法findNodeWithID不起作用。知道为什么吗?

3 个答案:

答案 0 :(得分:3)

它还不是语言的一部分,请使用babel

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

答案 1 :(得分:1)

为了使用箭头函数作为类属性,您需要添加transform-class-properties插件,如上所述 here.

答案 2 :(得分:0)

如果您希望findNode位于Tree的原型中,请使用常规函数:

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

或直接将其分配给原型:

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

如果希望将findNode初始化为属性,请在构造函数中执行:

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

或者使用TypeScript,它将允许您使用的语法。

当您在函数中引用this时,您不希望它是箭头函数,因为它不会有this上下文

相关问题