簡體   English   中英

JavaScript嵌套函數原型范圍

[英]JavaScript nested function prototype scope

我仍然無法確定如何在JavaScript中管理范圍。 在這個特定的例子中,我有一個包含某些屬性的繪圖函數和一個需要根據數組繪制線條的函數。

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

當然,forEach函數中的“this.ctx”返回“undefined”。 如何確保將Draw()的變量傳遞給forEach函數(不執行類似ctx = this.ctx的操作)?

你可以使用.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));

了解更多關於this

將對象實例變量聲明為方法范圍內的新變量是很常見的:

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

這有讓您可以繼續使用的優勢, this因為這將是一般。

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

第二個參數在回調中設置this的值。


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM