根据以下代码,如何在画布点击事件中调用函数searchBlock()
?this.searchBlock()
无法在此处工作!
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;
}
}
}
}
答案 0 :(得分: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){
...
}
}