簡體   English   中英

使用此方法訪問變量將返回map中未定義的

[英]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.mapreduce引用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();

我的問題是:

  • 為什么會出現此錯誤?
  • 有沒有更好的方法來訪問“類”變量?
  • 這可能是JavaScript作用域錯誤嗎?

根據Array.prototype.mapMDN文檔

如果提供了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.

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