I'm using the extremely useful local fat arrow to preserve this
context in callbacks. However, sometimes I need to access the value that this
would've had if I hadn't used the fat arrow.
One example are event callbacks, where this
has the value of the element that the event happened on (I'm aware that in this particular example you could use event.currentTarget
, but lets assume you can't for the sake of an example):
function callback() {
// How to access the button that was clicked?
}
$('.button').click(() => { callback() });
Note: I've come across this question which deals with this exact same issue, but in CoffeeScript.
In a type position, => defines a function type where the arguments are to the left of the => and the return type is on the right. So callback: (result: string) => any means " callback is a parameter whose type is a function.
In short, with arrow functions there are no binding of this . In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions the this keyword always represents the object that defined the arrow function.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .
You could write a decorator function that wraps a fat-arrow function inside another function which allows the access to the usual this
and passes that value to the fat-arrow function as an additional argument:
function thisAsThat (callback) {
return function () {
return callback.apply(null, [this].concat(arguments));
}
}
So when you call thisAsThat
with a fat-arrow function, this basically returns a different callback function that, when called, calls the fat-arrow function with all the arguments but adds this
as an argument in the front. Since you cannot bind fat-arrow functions, you can just call bind
and apply
on it without having to worry about losing the value.
You can then use it like this:
element.addEventListener('click', thisAsThat((that, evt) => console.log(this, that, evt)));
This will log the this
of the current scope (as per fat-arrow rules), the this
of the callback function as that
(pointing to the element for event handlers), and the event itself (but basically, all arguments are still passed on).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With