2016-12-02 98 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

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

這樣做。使用正確的工具來完成這項工作。

相關問題