Tuesday, March 4, 2008

Moose in JavaScript

This must have been done before, but it was fun anyway. I have written a partial implementation of Moose (and Class::MOP) in JavaScript. It's called Joose. It is self-hosting, so you can write meta classes in Joose and you get some of the syntactic sugar from Moose.

A typical example would be:


Class("Animal");

methods({
multiply: function () { return this.meta.instantiate() }
})

Class("Cat");
isa(Animal)

methods({
likes: function () { return "fish" }
})

Class("Dog");
isa(Animal)
has("owner", {is: rw})

methods({
balksAt: function () { return this.owner },
hates: function () { Cat }
})

ok(Cat.meta.isa(Animal), "Cats are animals");
ok(Dog.meta.isa(Animal), "Dogs are animals too");
ok(!Animal.meta.isa(Cat), "Not all animals are cats")
ok(new Cat().likes() == "fish", "Cats like fish");
ok(new Cat().multiply().likes() == "fish", "Cat babies like fish")
ok(new Cat().multiply().meta.isa(Cat), "Cat babies are Cats")
Post a Comment