Friday, May 2nd, 2008
Emulating get, set, catchall for all browsers
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:
- var o = CGSobject(function (x) { return x+1; });
- // basic set
- o("a", 7);
- // basic get
- print(o("a"));
- // -> 7
- // getter
- o("b", {get: function () { return this.a+1;}});
- print(o("b"));
- // -> 8
- // setter
- o("c", {set: function (x) { this.a = x / 2 }});
- o("c", 50);
- print(o("a"));
- // -> 25
- // catchall
- print(o(2));
- // -> 3
- print(o("foo "));
- // -> "foo 1"
To get this, he used:
- function CGSobject (catchall) {
- var o = function (k,v) {
- if (v) {
- var curv = o.content[k];
- (curv && curv.set && curv.set.call(o.content,v)) || (o.content[k] = v);
- } else {
- var v = o.content[k] || o.catchall(k);
- return (v.get && v.get.call(o.content)) || v;
- }
- }
- o.content = {};
- o.catchall = catchall || function () { return null };
- return o;
- }





3.1 rating from 14 votes
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.
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