4

I was wondering if there is a way to imitate PHP's magic methods __get() and __set() in Node. From this question: JavaScript getter for all properties I know you can do it in Rhino, but Node's built on V8. Does V8 have some way of doing this?

Community
  • 1
  • 1
Matt
  • 22,224
  • 25
  • 80
  • 116

3 Answers3

3

I believe you're out of luck, at least as of March 2010. At least you have __defineGetter__ and __defineSetter__, though I realize that's not the same thing. In general I think using __noSuchMethod__/__get/method_missing is not good since it makes the code harder to read. Consider trying to get by without it and see if it makes your code clearer.

Brian Donovan
  • 8,274
  • 1
  • 26
  • 25
  • Thanks Brian! I'll just try those methods and see if they will work. I think they would make the code harder to read if they were all over the place, but I think there are significant use cases if these methods are used internally. I like the prospect of being able to setup chains like this: `Message().action('join').groups([...]).message('Hi world!').send()` where some of these methods aren't defined and if they aren't append to an internal object. – Matt Dec 31 '10 at 20:15
  • 1
    Chaining and method missing stuff are unrelated. As long as `Message` instances define `action`, `groups`, `message`, and `send` to return `this`, it'll work fine. Obviously you can't have dynamic methods, but that's the price you pay I guess. Why I think it'd be hard to read isn't because you're using `__noSuchMethod__`, but because you'd be taking advantage of them everywhere. Let's say the `message` function above is one such dynamic function, and I want to see where it's defined. I can't just search for the function definition, I have to understand that there's a dynamic handler in play. – Brian Donovan Jan 01 '11 at 00:41
  • Whoops. I think I forgot to respond to this. I totally agree that they're unrelated, *unless* they aren't defined in Message, as you said. I want those to be attributes defined on-the-fly that can be chained together. I think this style of syntax for building up objects is damn sexy :-) – Matt Aug 11 '11 at 02:42
2

No answer? Check out nowjs. They seem to have found a way to make __get() and __set() work in JavaScript. I can't figure out how they do it from the source code. :(

EDIT: Check out Monitor All JavaScript Object Properties (magic getters and setters)

Community
  • 1
  • 1
BMiner
  • 16,669
  • 12
  • 53
  • 53
1

Have a look at my following answer that explains how one might tackle this with the use of ES6 proxies.

D. Ataro
  • 1,711
  • 17
  • 38