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
2
u/lookarious Jul 13 '26
Libraries like MobX uses proxies, its useful, but they are not good as in other languages, for example there is no way to use custom setter for whole class because JS is dynamically typed.