Ruby Style attr_reader and attr_writer in JavaScript

written by trotter on May 4th, 2009 @ 06:38 PM

So I’m playing around with a JavaScript URI parsing library right now, and decided it would be fun to implement Ruby’s attr_reader and attr_writer in JavaScript. It turned out to be pretty simple, with the only tricky part being dealing with the capturing the current value of a variable in my closure.

Check it out:

var attrReader, attrWriter, private;

private = {};

attrReader = function () {
    var i, anon, methods;
    methods = arguments;
    for (i = 0; i < methods.length; i += 1) {
        anon = function () {
            var j = i;
            that[methods[j]] = function () {
                return private[methods[j]];
            };
        }();
    }
};

attrWriter = function () {
    var i, anon, methods;
    methods = arguments;
    for (i = 0; i < methods.length; i += 1) {
        anon = function () {
            var name, method;
            name = methods[i]
            method = "set" + name[0].toUpperCase() + name.substring(1, name.length);
            that[method] = function (val) {
                private[name] = val;
            };
        }();
    }
};

attrReader("scheme", "host", "userInfo", "port", "path",
           "queryString", "fragment");
attrWriter("scheme", "host", "userInfo", "port", "path",
           "queryString", "fragment");

As a word of warning, this whole thing is probably terribly slow. Oh well, it’s really just for fun.

Comments

  • Mat Schaffer on 04 May 21:11

    Funny that you should mention it. Jeff Avallone and I ping-ponged a jQuery version of attr_accessor as well: http://github.com/matschaffer/jquery_attr_accessor Your use of "that" is new to me. Does that really work? { get foo() { } } also surprised me recently too http://ejohn.org/blog/javascript-getters-and-setters/

Comments are closed

Options:

Size

Colors