-4

I'll pick a random element form an Array in my Node.JS server application. I also use the arrow syntax of ES6. In the prototype of the object I've added a function named random(). Below you could find my code:

Array.prototype.random = () => {     // --> add element to prototype of `Array` object
    let rnd = Math.random();         // --> gives me a random number between 0 and 1
    let len = this.length;           // --> `this.length` gives `undefined`
    let naam = rnd * len - 1;        // --> result is `NaN`
    let numb = Math.floor(naam);     // --> `numb` is also `NaN`
    let arr = this;                  // --> `arr` contains an `Object` with none 
                                     //     properties or elements but `this` contains 
                                     //     the elements and the length.
    let el = arr[numb];              // --> `el` is `undefined`
    return el;                       // --> returns the random picked element
};

However I debug the code I see that the keyword this gives me an empty object. In the watch list I've added the value arr and I see this:

Watch variable arr

However the array contains two elements, two strings that represents API keys.

this contains two elements

What is wrong with my code?

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
  • First thing that jumps out is that you're using fat arrow syntax for a function on the prototype - is that intentional? – Daniel Dec 19 '16 at 08:45
  • There's already an answer so I'll just comment on a detail: don't directly assign a property to the prototype, use Object.defineProperty so that your property isn't enumerable – Denys Séguret Dec 19 '16 at 08:48
  • @Daniel: I use the arrow syntax because I use ES6. – H. Pauwelyn Dec 19 '16 at 08:52
  • 1
    @H.Pauwelyn That would be an awfully common misconception, I'm afraid. Fat arrow functions are not just a short syntax for traditional functions. You may wish to read more about it: http://exploringjs.com/es6/ch_arrow-functions.html – E_net4 Dec 19 '16 at 09:08
  • Related: [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) – Felix Kling Dec 19 '16 at 17:03

1 Answers1

8

Typically arrow functions are not used for prototype functions because as you found out, you won't get the correct this to be able to access instance properties/methods. Arrow functions inherit this from the parent context.

mscdex
  • 104,356
  • 15
  • 192
  • 153