2016-07-16 51 views
0

我有一個擴展另一個類的類。但是在試圖引用「this」的父類中定義的函數會拋出一個聲明「this」的異常未定義。下面是相關代碼:Js繼承了類實例undefined

class Entity { 
    constructor() { 
     this.axes = ['x', 'y']; 
     ... 

    updatePosition() { 
     this.axes.forEach(function(axis) { 
      this.position[axis] += this.velocity[axis]; 
     }); 
    } 
} 

class Player extends Entity { 
    constructor() { 
     super(); 
     .... 
    } 
... 
} 

var player = new Player(); 

和錯誤拋出:

.../player.js:25 
      this.position[axis] += this.velocity[axis]; 
       ^

TypeError: Cannot read property 'position' of undefined 

你知道爲什麼是實例未定義的,我怎麼能解決這個問題? 謝謝!

回答

1

forEach函數的背景下this是全局對象而不是玩家實例。由於您使用ES6你可以通過改變箭頭的功能,像這樣解決的:

updatePosition() { 
    this.axes.forEach((axis) => { 
     this.position[axis] += this.velocity[axis]; 
    }); 
} 

在這裏閱讀更多,在「這個詞」:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

+1

或者你可以引用'self'變量指向'this'在forEach函數之上,並且forEach內部使用'self'變量。 – atrifan

+0

好的,我明白了。我討厭javascript ... – nodwj

+0

是的,我們都做;) – apieceofbart