2012-10-04 96 views
3

之前我什麼也沒有,我很高興加入這個偉大的社區。關鍵是,我有一個叫做字一個JavaScript類是這樣的:在JavaScript類中調用父方法

var Character = function() 

{ 

    // ..Some previous Properties/Methods (included one called "StareDown()").. 

    // And this method: 

    this.GrabDown = function() 

    { 
     Context.clearRect(0, 0, CanvasWidth, CanvasHeight); 
     //Context.fillRect(0, 0, CanvasWidth, CanvasHeight); 
     Context.drawImage(this.GrabbingDown, CharacterX, CharacterY, SpriteWidth, SpriteHeight); 

     window.setTimeout 
     (
      function() 

      { 
       // Here is where I want to call the parent class method "StareDown()", but I don't know how.     
      }, 
      250 
     ); 
    } 
} 

所以這是我的大問題,我怎樣才能通過該子匿名函數訪問父類的方法?我一直試圖弄清楚整個晚上,但我找不到一些有用的信息,謝謝!

回答

1

您需要存儲在一個變量的父this對象(假設你已經定義的功能this.StareDown = function() {...}

var Character = function() 

{ 

    // ..Some previous Properties/Methods (included one called "StareDown()").. 
    this.StareDown = function() {...} 

    var curCharacter = this; 

    this.GrabDown = function() 

    { 
     Context.clearRect(0, 0, CanvasWidth, CanvasHeight); 
     //Context.fillRect(0, 0, CanvasWidth, CanvasHeight); 
     Context.drawImage(this.GrabbingDown, CharacterX, CharacterY, SpriteWidth, SpriteHeight); 

     window.setTimeout 
     (
      function() 

      { 
       // Here is where I want to call the parent class method "StareDown()", but I don't know how.  
       curCharacter.StareDown(...);   
      }, 
      250 
     ); 
    } 
} 
+0

明亮,這是最簡單的方法,只是將我的這個分配給一個名爲Parent的var,然後在您向我展示時通過它調用該方法,非常感謝。 – Neo

0

你可以只使用window.setTimeout(this.StareDown,250);但裸記住,該方法將在被稱爲全局上下文(即這將指向window,而不是調用該GrabDown方法Character實例

爲了使用功能作爲一個對象的方法:

window.setTimeout((function(that) 
{ 
    return function() 
    { 
     return that.StareDown(); 
    } 
})(this),250); 

應該工作。這是相當冗長,也許看MDN文檔的callapply尤其是bind可能證明是有用的

0

這是我會做:

var Character = function() { 
    this.GrabDown = function() { 
     setTimeout(function() { 
      // call this.StareDown in here 
     }.bind(this), 250); 
    }; 
}; 

這工作,因爲我們正在結合的this指向匿名FunctionExpression傳遞給setTimeout。因此它可以像班級的普通方法一樣使用。