[英]Accessing variable with this returns undefined in map
我收到錯誤消息:
Uncaught TypeError: Cannot read property '1' of undefined
運行以下命令時:
function Polygon(width, height) {
this.width = width;
this.height = height;
this.a = [1, 2, 3, 4, 5];
this.build = function() {
this.a.map(function(i, v) {
console.log(this.a[v])
});
}
}
var square = new Polygon(300, 300);
square.build();
僅當嘗試在Array函數(例如Array.prototype.map
和reduce
引用this.a
變量時,才會發生這種情況。 但是,將變量存儲在局部變量中時,代碼可以工作,如下所示:
function Polygon(width, height) {
this.width = width;
this.height = height;
this.a = [1, 2, 3, 4, 5];
this.build = function() {
var b = this.a;
b.map(function(i, v){
console.log(b[v])
});
}
}
var square = new Polygon(300,300);
square.build();
我的問題是:
根據Array.prototype.map
的MDN文檔 :
如果提供了
thisArg
參數來進行映射,則在調用該參數時會將其傳遞給回調,以用作其this值。 否則,將傳遞未定義的值作為此值。 (已強調)
這意味着map
函數中的this
是未定義的,因此您嘗試在undefined
上使用括號符號。 這將產生TypeError
,表示您正在嘗試訪問undefined
屬性。
您也錯誤地使用i
。 i
是實際的元素或項目 ,而不是索引。 您可以只需登錄i
,不要下標a
:
function Polygon(width, height){ this.width = width; this.height = height; this.a = [1, 2, 3, 4, 5]; this.build = function(){ this.a.map(function(i, v){ console.log(i); }, this); } } var square = new Polygon(300, 300); square.build();
這將傳遞可選的thisArg
作為Polygon
的上下文並正確記錄。 該參數明確聲明了this
上下文,從而允許訪問this.a
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.