我以为我已经修复了它,但看起来没有。发生了什么事:
canvas.mousemove
事件由 viewport.onMouseMove.bind(viewport)
处理函数(视口(viewport)是类的实例)。
在 onMouseMove
的末尾它调用的函数 this.Draw()
(引用viewport.Draw()
函数)。
viewport.Draw()
循环遍历所有项目并调用 Items[i].Draw(ctx)
他们每个人的位置 ctx
是后台缓冲区 Canvas 上下文。
现在,如果正在绘制的项目继续并使用 ctx 在那里绘制一些内容,然后(在其 Draw 函数中)使用 this 来引用自身,则一切正常。例如
this.Draw = function(ctx) {
ctx.beginPath();
ctx.moveTo(this.x1, this.y1);
ctx.lineTo(this.x2, this.y2);
ctx.lineWidth = 1;
ctx.strokeStyle = "#000000";
ctx.stroke();
};
但是,如果该对象是一个本身包含项目的容器,并尝试像这样循环和绘制它们
this.Draw = function(ctx) {
for (j = 0; j < this.Items.length; j++) {
this.Items[j].Draw(ctx);
}
};
当它进入Items[j].Draw
时,“这个”就失去了一切意义。 alert(this)
产生“对象对象”,我无法弄清楚它指的是什么(它不是视口(viewport),也不是容器,也不是它需要的项目)。还有另一个奇怪的事情 - 我必须更改容器对象循环以使用 j
而不是i
因为否则它将创建一个永久循环(就像 viewport.draw
和 item[i].draw
的 i 是相同的)。
最佳答案
你的问题有点不清楚。 this.Items
是与 this
具有相同原型(prototype)的对象数组吗? IE。嵌套?另外,j
计数器是否打算被共享?
无论如何,函数上下文的 this
值可以通过 .apply
和 .call
轻松更改为您需要的值功能:
this.Draw = function(ctx) {
for (var j = 0; j < this.Items.length; j++) {
// These two are the same as what you have in the question
this.Draw.call(this.Items[j], ctx);
this.Draw.apply(this.Items[j], [ctx]);
// This is what you had in the question if Draw is different for Items:
this.Items[j].Draw(ctx);
this.Items[j].Draw.call(this.Items[j], ctx);
// Will preserve the this reference within the nested call
this.Items[j].Draw.call(this, ctx);
}
};
关于javascript - 这又迷路了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24746539/