2013-02-11 96 views
2

我仍然有問題搞清楚如何在JavaScript的管理範圍。在這個特定的例子中,我有一個包含某些屬性的繪圖函數和一個需要根據數組繪製線條的函數。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(); 
    }); 
} 

當然, 「this.ctx」 在foreach內部函數返回 「未定義」。我怎樣才能確保抽獎()的變量傳遞給在foreach功能(沒有做這樣的事情CTX = this.ctx)?

回答

7

您可以使用.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.

3

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

+1

+1。不知道'forEach'支持它,但它確實:http://es5.github.com/#x15.4.4.18。 – 2013-02-11 01:34:27

4

是很常見的對象實例變量聲明爲法範圍內一個新的變量:

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

這有讓您可以繼續使用this的優勢正如通常那樣。