Friday, May 2nd, 2008

Emulating get, set, catchall for all browsers

Category: JavaScript, Library

Adrien Friggeri likes the true get, set, and catchalls that almost all but IE provide, so he took a peak at the examples and got to work emulating the layer, which ended up with:

javascript

  1. var o = CGSobject(function (x) { return x+1; });
  2.  
  3. // basic set
  4. o("a", 7);
  5.  
  6. // basic get
  7. print(o("a"));
  8. // -> 7
  9.  
  10. // getter
  11. o("b", {get: function () { return this.a+1;}});
  12. print(o("b"));
  13. // -> 8
  14.  
  15. // setter
  16. o("c", {set: function (x) { this.a = x / 2 }});
  17. o("c", 50);
  18. print(o("a"));
  19. // -> 25
  20.  
  21. // catchall
  22. print(o(2));
  23. // -> 3
  24. print(o("foo "));
  25. // -> "foo 1"

To get this, he used:

javascript

  1. function CGSobject (catchall) {
  2.   var o = function (k,v) {
  3.     if (v) {
  4.       var curv = o.content[k];
  5.       (curv && curv.set && curv.set.call(o.content,v)) || (o.content[k] = v);
  6.     } else {
  7.       var v = o.content[k] || o.catchall(k);
  8.       return (v.get && v.get.call(o.content)) || v;
  9.     }
  10.   }
  11.   o.content = {};
  12.   o.catchall = catchall || function () { return null };
  13.   return o;
  14. }

Posted by Dion Almaer at 10:27 am
2 Comments

+++--
3.1 rating from 14 votes

2 Comments »

Comments feed TrackBack URI

From TFA:

“The syntax isn’t really nice, but it’s usable.”

Uh, isn’t the point of getters and setters that the syntax is overloaded? Having to use different syntaxes for different browsers is not a win. You still need to maintain two code bases (or use an unintuitive syntax) for different javascript engines.

Comment by AndyB — May 2, 2008

Look at this library:
http://code.google.com/p/doufu/wiki/OOPWithDoufu
It also implemented a getter and setter (in the Property section), the getter and setter support implicitly convert to string and integer

Comment by normanzb — May 6, 2008

Leave a comment

You must be logged in to post a comment.