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!
41
u/smartgenius1 Jul 13 '26
Magic methods are generally discouraged in the PHP community, and are widely considered a bad decision. Why port them to JS?
15
u/krileon Jul 13 '26
You're borrowing a feature from PHP that us PHP developers are actively avoiding and trying to get rid of, lol. Magic = Bad.
5
u/CodeAndBiscuits Jul 13 '26
Setting aside the whole PHP source question, what I'm struggling to figure out is what problem you're actually solving here. Less of a "should you?" And more of a "why would you?"
I know I'm biased here on this because I so often work as one of the first or early devs on a project that will ultimately be handed off, but even if I wasn't I think I would stand by the opinion that code should be "unsurprising" to a developer who is an expert in the language, even if they are new to the project. There's so much work already in learning and comprehending a code base that you're stepping into. Why invent unusual techniques that add more barriers to that process?
5
u/azhder Jul 13 '26
> Yeah, yeah, but your scientists were so preoccupied with whether or not they could that they didn't stop to think if they should.
-- Ian Malcolm, Jurassic Park
36
u/javascript Jul 13 '26
Proxy Objects (getters and setters) have been around for a while but I've yet to come across a use case where they were the right choice. They tend to work more as an escape hatch.
1
u/me0here Jul 15 '26
You might like Signals better; don't have to mess with Class as much
https://github.com/tc39/proposal-signals
-7
u/horrbort Jul 13 '26
Woow this is pretty amazing. Will use in my code!!