JavaScript 嵌套函数原型作用域 [英] JavaScript nested function prototype scope

查看:47
本文介绍了JavaScript 嵌套函数原型作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm still having trouble figuring on how to manage scopes in JavaScript. In this particular example, I have a draw function containing certain properties and a function that needs to draw lines based on an array.

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();
    });
}

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

Of course, "this.ctx" inside the forEach function returns "undefined". How can I make sure that Draw()'s variables are passed to the forEach function (without doing something like 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));

详细了解this.

这篇关于JavaScript 嵌套函数原型作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆