2016-12-02 99 views
0

我有一个简单的原型继承构造函数,我正在使用箭头函数。JavaScript:在ES6中使用`this`与原型和箭头函数

app.Node = function (name, type) { 
    this.name = name; 
    this.type = type; 
    this.children = []; 
} 

app.Node.prototype = { 
    addChild: (child)=>{ 
     child._parent = this; 
     this.children.push(child); 
    }, 
    removeChild: (child)=>{ 
     this.children.forEach((item, i) => { 
      if (item === child) { 
       this.removeChildAtIndex(i); 
      } 
     }); 
    }, 
} 

然而,由于this和箭头功能性质,this值为undefined上面的原型的方法之内。那么我能以这种方式使用箭头功能吗?我不知道我需要改变什么,除了使用正常的function函数。

+0

你很好地掌握了箭头和普通函数的区别。箭头功能不仅仅是捷径。在你的特定情况下,可以使用方法的快捷方式,https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Method_definitions – estus

回答

2

那么我能用这种方式使用箭头功能吗?

编号箭头函数从声明它们时捕获值this

我不知道我需要改变,除了使用正常的功能函数。

这样做。使用正确的工具来完成这项工作。

相关问题