JavaScript nested function prototype scope -
i'm still having problem figuring on how manage scopes in javascript. in particular example, have draw function containing properties , function needs draw lines based on 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" within foreach function returns "undefined". how can create sure draw()'s variables passed foreach function (without doing ctx = this.ctx)?
you can utilize .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 this
.
javascript scope prototype
No comments:
Post a Comment