usr123
usr123

Reputation: 37

Getting a unexpected output

function normalize() {
   console.log(this.coords.map(function(x){
      return x/this.length;
 }));
}

normalize.call({coords: [0, 2, 3], length: 5});

Expected output: [0,0.4,0.6]

Output:[NaN, Infinity, Infinity]

Can someone explain the error?

Upvotes: 1

Views: 31

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386604

You need to take this along with the function for mapping with Array#map. Without thisArg, the callback has no access to this.

function normalize() {
    return this.coords.map(function (x) {
        return x/this.length;
    }, this);
}

console.log(normalize.call({ coords: [0, 2, 3], length: 5 }));

Upvotes: 1

Related Questions