Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototype, array extension, and object property

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.

like image 531
mfrachet Avatar asked Sep 04 '26 22:09

mfrachet


1 Answers

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);
    };
like image 99
Davin Tryon Avatar answered Sep 07 '26 11:09

Davin Tryon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!