Transcript from the "Fixing this in Classes" Lesson
[00:00:15] I don't know if it's ever gonna happen, but I think there is a proposal for a class decorator called @bound, which would make all your class methods auto-bound. So this is at least something that they're considering doing at some point, is making it so that you can opt into this auto-bound.
[00:00:31] And you probably can tell from my tone, at this point, that I don't think that's a great idea. But I wanna illustrate why it's such a bad idea through a code thought experiment. I sat down and I thought, how would we make it so that we could have methods on a prototype, but somehow also have auto hardbound methods that respond to the instances?
[00:00:56] And I came to the conclusion, there's a hack for this. And here's what it looks like. What we will do is, and I'm not expecting you to read this code. I could zoom in if you were really interested, but I'm not expecting you to read this code. It's just that this particular utility method takes an existing method on one of your prototype objects, and replaces it with a getter.
[00:01:21] So in other words, instead of having your real method on your class prototype, you're gonna have a getter. So when you access that property name through the getter, it automatically creates a hard bound method for you on the fly, and then saves it into a WeakMap. So it caches it into a WeakMap and then sends it out to you through by way of a getter.
[00:01:45] In other words, the getter is acting like a proxy to automatically vend these hard bound or these auto hard bound functions for you. And so you get the benefit of having a function on the prototype that can be inherited. But every time you access it as a context dot, you're gonna get a hard bound version of it.
>> Kyle Simpson: Here's how you use that by the way, this crazy little utility.
[00:02:49] You can use it by simply calling that bind methods utility on the prototype of any class. And it'll automatically go through all of your class prototype methods, and replace them with getter versions that do the auto-bind method. And to my horror, I tweeted this out the other day to say hey, this is a really bad idea and here's why.
[00:03:13] And then I got several responses from people saying I'm now using this in my projects.
>> Speaker 2: [LAUGH]
>> Kyle Simpson: So,
>> Kyle Simpson: One of the famous quotes, I don't even know who to attribute it to, but famous quotes that I love is there's nothing more permanent than a temporary hacker.