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.
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With