2017-03-07 68 views
2

嗨,大家好我有這樣的代碼的JavaScript OOP的知名度

class Player { 
         constructor(posX, posY, spdX, spdY, width, height, image){ 
          // Vytvoření hráče 
          this.posX = posX; 
          this.posY = posY; 
          this.spdX = spdX; 
          this.spdY = spdY; 
          this.width = width; 
          this.height = height; 
          this.image = image; 
         }  
         // Draws player 
         draw(){ 
          var imageObj = new Image(); 
          imageObj.src = this.image; 
          ctx.drawImage(imageObj, testPlayer.posX, testPlayer.posY); 
         } 
         jump(){ 
          this.move('up'); 

         } 
         // Move 
         move(direction){ 
          // Returns false if fails 
          switch(direction){ 
           case 'right': 
            this.posX+= this.spdX; 
            break; 
           case 'left': 
            this.posX-= this.spdX; 
            break; 
           case 'up': 
            this.posY-= this.spdY; 
            break; 
           case 'down': 
            this.posY+= this.spdY; 
            break; 
           default: 
            return false; 
          } 
         } 
        } 

我在跳法問題。 當我想跳起來,我必須上下,但我怎樣才能做到這一點。 因爲我試圖setTimeout(function(){})但是在那個函數關鍵字裏面不能看到方法移動。如果我做setTimeout(this.move('down'),500)它不起作用。那麼有什麼想法?

回答

2

您需要的功能,具有正確的上下文。一種簡單的方法是使用ES6箭頭函數(caniuse)。他們將保留從您最初定義的函數this背景:

setTimeout(()=>{this.move('down')}, 500) 

或者,如果你想使用常規的功能,使用Function.prototype.bind()到this上下文綁定。這樣一來,當函數最終被調用時,上下文就是當你叫.bind的this(本)

function goDown(){this.move('down')} 
setTimeout(goDown.bind(this)) 
1

問題是setTimeoutcallback導致值this發生變化。

您可以通過執行保存this

var that = this; 
setTimeout(function() { 
    that.move('down'); 
}, 500); 
+0

您好感謝的作品,我將迎來後6分鐘 –

+0

良好的解決。如果你使用babel,或者是針對ES6瀏覽器,我會推薦使用@James Kraus的答案,因爲它更乾淨。 –