39 ms·
I'm not entirely sure what this adds in this case, though. For example, in the code you've written, as far as I can tell there's no advantage compared to defini
by MrJohz 3y ago
I'm not entirely sure what this adds in this case, though. For example, in the code you've written, as far as I can tell there's no advantage compared to defining the function as a closure variable and using it directly, rather than defining it as an attribute on `this` and passing the `this` object around.
In addition, with the `handleEvent` approach, you need to handle all events within a single function. But it's fairly easy to create multiple functions within a single function scope and pass them to different event handlers, thus avoiding the need for the large (and potentially error-prone) switch statement if you end up needing to handle lots of events.
Have you found cases where `handleEvent` works better than just defining local variables within a function and just using those? It seems to me that you wouldn't even need arrow functions to take advantage of the natural power of closures in this context.
- masswerk 3y agoOne of the advantages is that this can be defined and handled on the prototype level and not just in the instance. Personally, I'd see the interrupt-like catch-all behavior rather as an advantage (all messages are received in a single slot), but this may be up to personal taste. And, while it's true that similar binding can be achieved using closures, this has also been true for arrow functions. It's just a convenient solution in the mindset of the original ECMA Script (ECMA 262-2). Regarding prototypes, mind how this shares methods between instances, rather than consuming (and locking) resources by individual closures created in each of the instances (which, when GC was still based on reference count, would also have meant memory leaks): function Counter(buttonElement) { this.clicked = 0; buttonElement.addEventlistener("click", this, false); } Counter.prototype = { reset: function() { this.clicked = 0; }, log: function() { concole.log("I was clicked " + this.clicked + " times."); }, handleEvent: function(event) { this.clicked++; this.log(); } };
- throw-the-towel 3y agoClosures really are poor man's objects.
- MrJohz 3y agoAnd vice versa!