r/javascript 9d ago

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!

13 Upvotes

46 comments sorted by

View all comments

Show parent comments

11

u/jhartikainen 9d ago

It seems potentially valuable in some kind of framework/infra code. Svelte uses them for its $state runes for example. But yeah, like generators, I've not really found any use for them myself.

6

u/javascript 9d ago

Oh ya generators haha. I was so bewildered by the `function*` syntax when I first learned it. What a wild land grab for such a niche feature.

3

u/alex-weej 9d ago

It's not that niche! Could have been a keyword though.

1

u/javascript 9d ago

What have you used generators for?

4

u/Kwantuum 8d ago

Generators were used to transpile async/await for years.

I've used generators on a number of occasions. Generally I avoid it unless it's a great fit for the problem because they remain a relatively obscure feature for most people. They're a great way to get support for for..of on custom containers, among other things.

The other problem with generators and iterators in general is the lack of standard library support for manipulating them. No standard iterator mapping/filtering really reduces their usefulness.