fflorent
2014-09-07
Named functions are practical to reference the function itself inside the function body. I use them mainly in two cases:
- Recursive
setTimeout
(a trick to do a propersetInterval
which automatically stops when an exception occurs) - Trigger an event listener just once
For the second, just consider this example:
var obj = {
listen_once: function() {
let self = this;
this.elem.addEventListener("click", function onFirstClick(ev) {
self.elem.removeEventLisnener("click", onFirstClick);
self.doStuff();
// ...
});
},
// ...
}
That’s a pity! Because arrow functions aims at getting rid of the let self = this;
(or the Function.prototype.bind()
) trick.
How about allowing naming arrow functions:
this.elem.addEventListener("click", onFirstClick(ev) => {
this.elem.removeEventListener("click", onFirstClick);
this.doStuff();
// ...
});
Note: I see that it has been deferred in the EcmaScript wiki page. Any reason for that? I write this post to stress how useful it would be to have named arrow functions.
Florent