3

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.

1 Answer 1

3

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);
    };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.