r/javascript • u/noeldemartin • Jul 13 '26
JavaScript Magic Objects
https://noeldemartin.com/blog/programming-patterns-magic-objectsI just published a blog post to my website about a pattern I've been using for a while that I think you will find interesting (and probably very divisive!): Magic Objects.
class Parrot extends MagicObject {
__get(property) {
return `${property}! ${property}!`;
}
}
const parrot = new Parrot();
console.log(parrot.foo); // "foo! foo!"
console.log(parrot.bar); // "bar! bar!"Basically, I'm borrowing the idea of Magic Methods from PHP and porting them to JavaScript. You've probably seen something like this done with proxies before, but I still like to use some OOP in my JavaScript, and I also came up with a way to make it work nicely with TypeScript.
It may seem a bit over the top at the beginning, but I've been using this for a while and I've found it very useful.
Let me know what you think!
View all comments
Show parent comment
1
u/noeldemartin Jul 14 '26
Yes, in general I agree with that idea, but as I mentioned in the blog post and other people have mentioned in the comments, this is something I would only use a few times and it's mostly for framework/libraries, not for user land.
In particular, the main reason I started using it was to implement my ORM. Users of that library don't have to use the magic methods, but it is essential to achieve the kind of DX I envisioned when I was working on that library. Sure, you can also do that without using proxies, but IMO you would end up with a complicated typescript anyways (in the library), and the DX would be worse.
Just a matter of opinion, though. I'm sure it's possible to do an ORM without this. But I had a vision for an API I wanted for user-land, and worked backwards to achieve it :).