Moose in JavaScript

malte on 2008-03-04T22:07:47

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")


Let see the source!

Stevan on 2008-03-04T22:52:59

I have been pondering something like this for a while, although to be honest I am not a fan of slapping on a class OO system to the already perfectly fine prototype OO system of JS.

Lets see some source though, I would be interested in knowing what hoops you had to jump though to make it work.

- Stevan

Re:Let see the source!

renodino on 2008-03-05T01:06:22

Megadittos!

This looks much better (sexier?) than the Java-esque hack I was trying to bolt on.

Will this be showing up on JSAN anytime soon ?

Re:Let see the source!

malte on 2008-03-05T06:20:18

This was a three hour project, so beware of zero documentation: Joose-Source

And here..

jk2addict on 2008-03-05T20:47:45

I thought I felt dirty when Catalyst::View::PHP came out. This trumps that. :-)

Re:And here..

Aristotle on 2008-03-11T08:12:33

Why? Unlike PHP, Javascript is actually a nice language. It has closures and syntax for regex literals, everything is an object, and it doesn’t confuse arrays with hashes. It doesn’t have lists or easy array flattening, and it’s usually syntactically more verbose than Perl, but usually semantically equally concise, because in many ways it is very similar to Perl.

I wouldn’t be unhappy at all if I was forced to write Javascript for the rest of my life.