Reputation: 8932
I m studying functionnal programming with Haskell, and I wanted now to use it with Javascript.
I have read that it's a great training to reproduce some basic functions with javascripts, like map or filter, so I decided to make them, again.
Actually I'have this code :
'use strict';
Array.prototype.map = (cb) => {
console.log(this); // get empty object
console.log(this.length); // get undefined
};
let array = [1, 4, 9];
array.map(Math.sqrt);
As you can see there, my problem is that I can't access the 'this' object in my map function, so I can't access my items inside of my prototypal function.
How can I process to access each of the items in my array inside of my map function ?
Thanks for your help.
Upvotes: 3
Views: 50
Reputation: 67316
This issue you are encountering is most likely caused by using the arrow function syntax =>
.
Arrow functions do not create a function scope and therefore inherit from the surrounding scope. In this case, it is the global/module scope. Since, you are using 'use strict'
, the this
globally should be undefined
.
Try to change your map
using the function
keyword:
Array.prototype.map = function(cb) {
console.log(this); // should now be scoped
console.log(this.length);
};
Upvotes: 3