JavaScript nested function prototype scope

随声附和 提交于 2019-12-11 02:33:33

问题


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


回答1:


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.




回答2:


It's common to declare the object instance variable as a new variable inside the method scope:

var self = this;
MAP.forEach(function (name) {
    self.ctx.moveTo(...

This has the advantage of allowing you to continue to use this as it would be ordinarily.




回答3:


Pass this as the second argument to forEach().

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

The second argument sets the value of this in the callback.


MDN forEach() docs - array.forEach(callback[, thisArg])



来源:https://stackoverflow.com/questions/14804718/javascript-nested-function-prototype-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!