KpTheConstructor KpTheConstructor - 2 months ago 8
Javascript Question

Accessing variable with this returns undefined in map

I'm getting error:

Uncaught TypeError: Cannot read property '1' of undefined


when running the following:

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();


This occurs only when trying to reference the
this.a
variable within Array functions such as
Array.prototype.map
and
reduce
. The code, however, works when storing the variable within local variable, like so:

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();


My questions are:


  • Why am I getting this error?

  • Is there a better way to access a 'class' variable?

  • Could this be a JavaScript scope bug?


Answer

Per the MDN documentation for Array.prototype.map:

If a thisArg parameter is provided to map, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. (Emphasis added)

This means that this in the map function is undefined, thus you're attempting to use bracket notation on undefined. This yields the TypeError, which says you're trying to access a property of undefined.


You are also incorrectly using i. i is the actual element or item, not the index. You can just log i, do not subscript 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();

This will pass the optional thisArg as the Polygon's context and log correctly. The argument explicitly states the this context, allowing the access of this.a.

Comments