4 ms·
>Yyyyyeah, classes in js are pretty bad full stop. For instance, passing a method as an argument will do awful things unless you bind it to a this first. Gross.
by imbnwa 3y ago
>Yyyyyeah, classes in js are pretty bad full stop. For instance, passing a method as an argument will do awful things unless you bind it to a this first. Gross.
One of the things that heavy use of JS frameworks will do is make you forget you can pass an object interface to represent continuations. The DOM spec defines the EventListener type, in TypeScript notation, as:
`(event: Event) => void | { handleEvent(event: Event): void }`
What does this type signature instruct us to think?
That a function closure should reference objects in its scope, no need for `this` binding, or an object interface, appropriate to the domain of the deferred caller should be referred to and called (e.g. `handleEvent` in the case of DOM's EventTarget interface, but one could also imagine `{ onTimeout() : void }` if the spec authors were consistent, perhaps accepting a key to differentiate calls in the same vein as event types), also eliminating the need to bind `this`. The addition of `WeakMap`\`WeakSet` to the runtime eliminates the need for manual resource management.
But React, the most popular JavaScript library (and its not alone in this), makes this pattern impossible: you can only pass functions to event listeners. So everyone then growls about `this` binding.