News for hackers. Stuff that matters.
Re:JS.Class - A Ruby Inspired JS Framework by sshumaker on Saturday March 27, 2010 @05:20PM (#1223704)
I implemented something like this for my last project, but I think you can make JS class creation far more ruby-like (and flexible, for that matter), by not passing an explicit hash to your class creation function, but instead building the class in a callback:

  // code start
  var Event = Class.define(function()
  {
    this.speak = function()
    {
       console.log("HI");
    }

    // since you can just write code in here
    // metaprogramming is easy:
    ["attack", "defend"].each(function(name) {
    this[name] = function() {console.log(name);}
    }.bind(this));

    // or build reusable metaprogramming facilities
    // and use them here
    this.$setters(["x", "y", "z"]);
    this.$memoize("expensiveFunc", function() {
         // blah
    });
    this.$inherited = function(derivedClass) { ... }
});

Basically, the class define method would create a special 'class-creation' object, and would invoke the user provided function with the class creation object as the this pointer. After the callback finished, I would use the class-creation object to build the actual class.

Being actual able to write code inside your class definition is a much more flexible way to define your objects - and it's also how Ruby does it.

There are no comments on this comment yet.