2014-10-29 90 views
0

在以下代碼中,如何在畫布單擊事件中調用函數searchBlock()this.searchBlock()不能在這裏工作!如何在javascript點擊事件之外調用函數

Board.prototype = { 
    addHandlerToBlock:function(){ 
     this.canvas.onclick = function(e){ 
      var e = window.event || e; 
      var rect = this.getBoundingClientRect(); 
      var mouseX = e.clientX - rect.left; 
      var mouseY = e.clientY - rect.top; 
      var clickBlockId = this.searchBlock(mouseX, mouseY) || -1; 
      if(clickBlockId >= 0){ 
       if(canMove(this.puzzle[clickBlockId])){ 
        alert("ha") 
       } 
      }   
      this.refresh(p); 
     } 
    }, 
    searchBlock:function(x, y){ 
     for(var i = 0; i < this.puzzle.length; i++){ 
      if(x - this.puzzle[i].x > 0 && y - this.puzzle[i].y > 0){ 
       return i; 
      }    
     } 

    } 
} 
+1

像這樣:var board = new Board(); var block = board.searchBlock(x,y);' – 2014-10-29 16:20:12

+0

在Board的原型函數中新建一個Board是否好? – 2014-10-29 16:27:28

+0

啊,不,不是。我以爲你的意思是一個外部點擊畫布onclick處理程序,我的錯誤。讓我發表更徹底的答案。 (它不一定總是壞的,但我認爲你是對的,想避免它。) – 2014-10-29 16:29:11

回答

1

試試這個。可能並不是絕對需要別名this變量,但我喜歡這樣做,因爲可以在爲this傳遞不同值時調用該方法。

Board.prototype = { 
    addHandlerToBlock:function(){ 
     var that = this; // alias to "this" 
     this.canvas.onclick = function(e){ 
      ... 
      var block = that.searchBlock(x, y); 
     } 
    }, 
    searchBlock:function(x, y){ 
     ... 
    } 
} 
+0

太棒了!我差點忘了這種方式!謝謝! – 2014-10-29 16:41:17

相關問題