1

can someone please explain the following:

I want to add a function to the Array prototype. I'm doing this in two ways:

// option1
Array.prototype.myFunc1 = function() {
  console.log(this);
}

// option2
Array.prototype.myFunc2 = () => {
  console.log(this);
}

[1, 2].myFunc1();
[1, 2].myFunc2();

In option1 'this' is the array. In option2 'this' is an empty object. What's the difference?

Any thoughts appreciated C

Cathal
  • 1,648
  • 16
  • 28
  • in `Option2` `this` will point to window object – Nemani Aug 31 '17 at 10:37
  • 1
    Please [search thoroughly](/search?q=%5Bjs%5D+arrow+function+this) before posting. More on searching [here](/help/searching). This question has been **repeatedly** asked and answered. – T.J. Crowder Aug 31 '17 at 10:37
  • 1
    @Nemani: Not necessarily. `this` will have the same value inside the arrow that it has outside it, which may or may not be a reference to the global object depending on where the code is and whether it's in strict mode or not. – T.J. Crowder Aug 31 '17 at 10:38
  • https://rainsoft.io/when-not-to-use-arrow-functions-in-javascript/ – Donal Aug 31 '17 at 10:38

0 Answers0