Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript nested function prototype scope

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

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)?

like image 896
Jack Guy Avatar asked Jun 15 '26 10:06

Jack Guy


1 Answers

You can use .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));

Learn more about this.

like image 101
Felix Kling Avatar answered Jun 17 '26 23:06

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!