Emulating catchall, getter and setter in JS

Getters and Setters are cool stuff, so is the notion of catchall. And, if it's a nice feature, it has to be implemented or emulated. I don't have nothing much to say about this except that I did it and that it works. The syntax isn't really nice, but it's usable. I used the same examples used here.

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;
}

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"

4 Responses to "Emulating catchall, getter and setter in JS"

Ajaxian » Emulating get, set, catchall for all browsers says:

[...] 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: PLAIN TEXT [...]

Peter Michaux says:

Building a new "send" for JavaScript is enticing. By building a custom send, any OO paradigm can be implemented with getters, setters, method missing, live mixins and aspect-oriented programming, etc. I've played with this (http://peter.michaux.ca/article/1174) but since the resulting syntax is so foreign to any other programmer and performance is slow, I've decided to work within the confines of the language itself. It sure is fun to play with these types of things, however.

Norman says:

look at this library:
http://code.google.com/p/doufu/wiki/OOPWithDoufu
also implemented a getter and setter and support implicitly convert to string and int

Norman says:

look at the "Property" section

Leave a Reply