javascript - 这又迷路了

标签 javascript this

我以为我已经修复了它,但看起来没有。发生了什么事:

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.drawitem[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/

相关文章:

javascript - 解码base64图像并上传

javascript - React Native 上的 DeviceOrientation 事件

javascript - 在 HAML 中包含 CSS 和 Javascript 的缺点

javascript - 折叠的导航栏下拉时如何更改背景颜色?

javascript - 是否可以从 iframe 中单击的链接获取 url?

javascript 函数 this 和原型(prototype)

c# - 在继承中使用 this() 和 base()

javascript - 使用此压缩多次点击和提交功能

Javascript 'this' 嵌套函数内的关键字

java - 使用 self(this) 参数在构造函数中调用构造函数