0

myRegFunc refers to this with local scope limited to users object. However, myArrowFunc instead refers to this with global scope. Is there a way to reference the same this information in the arrow function as is available from the regular function?

So the arrow func cannot bind to the local this? However, is it possible to still get the local this information through the global this? For example: global this.something.something ... = the local this.

const users = {
  name: 'John',
  myRegFunc: function() {
    console.log('myRegFunc : ', this);
  },
  myArrowFunc: () => console.log('myArrowFunc this: ', this),
};
users.myRegFunc();
users.myArrowFunc();

Output:

myRegFunc :  {name: 'John', myRegFunc: ƒ, myArrowFunc: ƒ}
arrowFunc.js:34 myArrowFunc this:  Window {window: Window, self: Window, document: document, name: '', location: Location, …}
Bill
  • 915
  • 2
  • 13
  • 23
  • 8
    No, that's one of the _points_ of arrow functions. If you want a regular function's behaviour, use a regular function. – jonrsharpe Oct 03 '21 at 18:32
  • OK, I can't bind to 'this' from the arrow func. However, is it possible to reference the local this from the global 'this' by drilling down a path? For example 'this.something.something.something ...'? – Bill Oct 03 '21 at 18:38
  • 1
    You have the reference. It is `users`. As for arrow functions, there is no such `this` reference *created*, so there is no generic way to reference it -- it just isn't there at all. Within arrow functions `this` has the same value as immediately around that arrow function. – trincot Oct 03 '21 at 18:47
  • Can you show an example that works? – Bill Oct 03 '21 at 18:48
  • 1
    It already "works" as intended. Just read the comment above and the linked duplicate reference that was put as the question was closed. – trincot Oct 03 '21 at 18:50
  • 2
    Er, you have an example that works in your question:, using a non-arrow function function. – Andy Oct 03 '21 at 18:51
  • Fair enough. A non-arrow is my only option. Thanks for the feedback. – Bill Oct 03 '21 at 18:51

0 Answers0