KpTheConstructor KpTheConstructor - 2 months ago 7
HTML Question

Class variable undefined ? Javascript bug?

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 refernce
this.a
class variable within any array function .map() , .reduce() ect..

but works when storing class 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();


1. Why am I getting this error ?

2. Is there a better way to access a class variable ?
3. Also , 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