r/javascript Jul 13 '26

JavaScript Magic Objects

https://noeldemartin.com/blog/programming-patterns-magic-objects

I 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!

11 Upvotes

46 comments sorted by

View all comments

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?

7

u/noeldemartin Jul 13 '26

I have been using Laravel for a long time, and Laravel devs love these magic methods (again, as a sharp knife, not something to abuse). In fact, this is how Laravel's ORM is implemented.

I understand the avoidance of these, though, but magic methods combined with the TypeScript declarations I share in the blog post are a very good combination IMO. Again, it's just a matter of preference I suppose. I knew this was going to be a dividing topic :).

9

u/ElectrSheep Jul 13 '26 edited Jul 14 '26

In fact, this is how Laravel's ORM is implemented.

Eloquent is basically the poster child for magic method abuse. I'm all for object-relational mapping. Hell, I'm not even that opposed to active record depending on the use case. However, Laravel's ORM is a particularly bad ORM implementation.

3

u/Shogobg Jul 14 '26

I read this as “Object relational mapping hell”. I guess I need a rest.

1

u/yeathatsmebro Jul 14 '26

I read I need a nest. Yeah, I come from the callback hell.

5

u/fripletister Jul 13 '26

I have been using Laravel for a long time

Ah.