admin管理员组文章数量:1277901
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)?
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)?
Share Improve this question edited Feb 11, 2013 at 1:31 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked Feb 11, 2013 at 1:30 Jack GuyJack Guy 8,5238 gold badges60 silver badges88 bronze badges3 Answers
Reset to default 7You 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
.
It's mon 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.
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])
本文标签: JavaScript nested function prototype scopeStack Overflow
版权声明:本文标题:JavaScript nested function prototype scope - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741239720a2363732.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论