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的操作)?
您可以使用.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)
| 归档时间: |
|
| 查看次数: |
2994 次 |
| 最近记录: |