JavaScript嵌套函数原型范围

Jac*_*Guy 2 javascript scope prototype

我仍然无法确定如何在JavaScript中管理范围.在这个特定的例子中,我有一个包含某些属性的绘图函数和一个需要根据数组绘制线条的函数.

function Draw (canvas)
{
    this.ctx = canvas.getContext('2d');
    this.street_size = 20;
}

Draw.prototype.street = function (MAP)
{

    MAP.forEach(function (name)
    {
        this.ctx.moveTo(name.start.x,name.start.y);
        this.ctx.lineTo(name.end.x,name.end.y)
        this.ctx.stroke();
    });
}
Run Code Online (Sandbox Code Playgroud)

当然,forEach函数中的"this.ctx"返回"undefined".如何确保将Draw()的变量传递给forEach函数(不执行类似ctx = this.ctx的操作)?

Fel*_*ing 7

您可以使用.bind [MDN]:

MAP.forEach(function (name) {
    this.ctx.moveTo(name.start.x,name.start.y);
    this.ctx.lineTo(name.end.x,name.end.y)
    this.ctx.stroke();
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

了解更多信息this.