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 /.../
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 /.../
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
; thethis
value of the enclosing execution context is used.
This behaviour is exactly the same as with lambda functions in other languages.
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) })
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.