0

Why arrow function fails to identify this pointer in the following case. I know that regular functions have their own execution scope and this but I could not identify why following failed. In the arrow function case, this is undefined. If someone can shed light, it would be great. Thank you!

PS: This code is just for experimental purposes, not anything serious.

const addProperty = function(op, func) {
  String.prototype.__defineGetter__(op, func);
};

// works
addProperty('upper', function() {
  return this.toUpperCase();
});

// fails to identify this
addProperty('lower', () => {
  return this.toLowerCase();
});
Validus Oculus
  • 2,756
  • 1
  • 25
  • 34
  • 1
    Found the answer after short Google search. :) https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions – Anand Pap Dec 04 '22 at 06:21

1 Answers1

2

Arrow functions preserve the this of the outside scope. function keyword functions, in this context, get the this of the object they're put on. That's just what they do.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • To add onto this, if you want to use the arrow function, simply use the `bind` method to explicitly set the `this` value for the arrow function: `addProperty('lower', () => { return this.toLowerCase(); }.bind(this));` – Andrew Shearer Dec 04 '22 at 06:23
  • 1
    @AndrewShearer Doing that does not work (partially because of the syntax error; you need to wrap that in parentheses) because that still binds it to the outside scope, because that's what the value of `this` is at that point – Samathingamajig Dec 04 '22 at 06:25
  • @AndrewShearer [You cannot rebind arrow functions](https://stackoverflow.com/q/33308121/1048572) – Bergi Dec 04 '22 at 06:28
  • and apparently, you can't rebind arrow functions, good to know, but it does not throw a warning/error/exception – Samathingamajig Dec 04 '22 at 06:28