使用此方法访问变量将在map中返回undefined

KpT*_*tor 1 javascript variables scope this

我收到错误:

Uncaught TypeError: Cannot read property '1' of undefined 
Run Code Online (Sandbox Code Playgroud)

运行以下内容时:

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();
Run Code Online (Sandbox Code Playgroud)

只有在尝试引用this.aArray函数(如Array.prototype.map和)中的变量时才会发生这种情况reduce.但是,代码在将变量存储在局部变量中时起作用,如下所示:

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();
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 为什么我收到此错误?
  • 有没有更好的方法来访问'class'变量?
  • 这可能是JavaScript范围错误吗?

Li3*_*357 5

MDN文件Array.prototype.map:

如果thisArg提供了一个参数来映射,它将在调用时传递给回调,以用作其值.否则,将传递未定义的值以用作其此值.(重点补充)

这意味着,thismap函数未定义,因此您试图上使用括号标记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();
Run Code Online (Sandbox Code Playgroud)

这将通过可选的thisArg作为Polygon的情况下,正确地记录.该参数明确说明了this上下文,允许访问this.a.