小编KpT*_*tor的帖子

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

我收到错误:

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

javascript variables scope this

1
推荐指数
1
解决办法
114
查看次数

标签 统计

javascript ×1

scope ×1

this ×1

variables ×1