[英]JavaScript nested function prototype scope
I'm still having trouble figuring on how to manage scopes in JavaScript. 我仍然无法确定如何在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". 当然,forEach函数中的“this.ctx”返回“undefined”。 How can I make sure that Draw()'s variables are passed to the forEach function (without doing something like ctx = this.ctx)?
如何确保将Draw()的变量传递给forEach函数(不执行类似ctx = this.ctx的操作)?
You can use .bind
[MDN] : 你可以使用
.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));
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. 这有让您可以继续使用的优势,
this
因为这将是一般。
Pass this
as the second argument to forEach()
. this
作为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. 第二个参数在回调中设置
this
的值。
MDN forEach()
docs - array.forEach(callback[, thisArg])
MDN
forEach()
docs - array.forEach(callback[, thisArg])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.