0

Is it possible to get the "old" this, like you would get with function()?

addEventListener("click", () => { console.log(this) }) // {}

addEventListener("click", function() => { console.log(this) }) // EventEmitter /.../
Glutch
  • 410
  • 4
  • 16
  • Read [How to Ask A Good Question on Stack Overflow](https://stackoverflow.com/help/how-to-ask) – cmprogram Oct 25 '17 at 09:27
  • I think this question would be way easier to read if you presented the expected behaviour first and the actual afterwards. Currently it's the other way around. – Hubert Grzeskowiak Oct 25 '17 at 09:28
  • [When should I use Arrow functions in ECMAScript 6?](https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6) – Andreas Oct 25 '17 at 09:46

3 Answers3

1

Arrow functions in JavaScript do not create a new context and therefore no "new" or "old" this. They are using whatever is available in their scope of definition.

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions:

An arrow function does not have its own this; the this value of the enclosing execution context is used.

This behaviour is exactly the same as with lambda functions in other languages.

Hubert Grzeskowiak
  • 10,887
  • 4
  • 47
  • 61
0

Your question was unclear to me.

If you want the current clicked element, use the property currentTarget on your event :

addEventListener("click", (e) => { console.log(e.currentTarget) })

If you want the previous this, just store it previously :

var that = this;
addEventListener("click", () => { console.log(that) })
Zenoo
  • 11,719
  • 4
  • 38
  • 57
0

I don't believe there is a way to make arrow function behave like this - preserving the current this is what it was designed for.

Your best solution is to just use function() {} when you need this to be provided to you.

UncleDave
  • 5,609
  • 1
  • 21
  • 41