2007 / July 16th/ MooTools Javascript Classes
One of Javascript’s major blunders when it comes to Object-Oriented design is the lack of true classes. Lucky for us, we’ve had every library author out there have their whack at creating a class structure.
What is a class?
A class is kind of a template. One of the big concepts of OO is treating your code as real world objects. Let’s say you want to have three variables for different dogs: ollie, rowdy, and killer. Each of these variables should be an instance of a class. That class’s name would be Dog. Each particular dog is an instance of the generic Dog class. I won’t go into much more detail here: there’s plenty of reading to do on what classes really are, and how to use them best.
MooTools = <3
Out of all the class systems I’ve used, I’d have to say MooTool’s class system (spanwed from Dean Edward’s Base) is the cleanest, most extensible system yet. Creating and extending classes is ridiculously easy.
Create a class
var Animal = new Class({
initialize: function(){
this.text = "Animal Runs!";
},
run: function(){
alert(this.text);
}
});
var pet = new Animal();
pet.run();
// ==> "Animal Runs!"
(It’s also fair to note that MooTools supports Prototype’s Class.create method as well)
Extend a class
var Dog = Animal.extend({
initialize: function(){
this.parent();
},
bark: function(){
this.run();
alert("Woof! Woof!")
}
});
var pet = new Dog();
pet.bark();
// ==> "Animal Runs!"
// ==> "Woof! Woof!"
You’ll notice you still get access to parent methods (through this.parent()), as you can see where this.text gets initialized when a new instance of Dog is created.
The syntax is short, sweet, and to the point. Furthermore it allows me all the flexibility I need… well, almost. MooTools team gets bonus points for the next section.
Javascript mixins… kinda
There are two common actions that many Javascript actions have: options, and callbacks. MooTools have created a sort of ruby-style mixin for classes to handle these functions. MooTools calls these mixins Utility Classes. To enable these, add this line to the code above:
Dog.implement(new Options, new Events);
Options
What does this do? First off, it allows for quick, easy, extendible options. All you do is set your default options in an options property, and then call the setOptions method inside your class. Here’s an example:
var Dog = new Class({
options: {
age: 5,
type: "Jack Russel Terrier"
},
initialize: function(name, options){
// Here's the magic!
this.setOptions(options)
this.name = name;
},
bark: function(){
alert("My name is " + this.name + " and I am " + this.options.age + " years old");
this.fireEvent('afterBark', this);
}
});
Dog.implement(new Options, new Events);
var ollie = new Dog('Ollie');
ollie.bark();
// ==> "My name is Ollie and I am 5 years old"
var rowdy = new Dog('Rowdy', {age:15});
rowdy.bark();
// ==> "My name is Rowdy and I am 15 years old"
By mixing in the Options methods, you now have access to setOptions, which either uses user-defined options or class-based defaults (with one line of code).
Events
You can also define custom events (usually called callbacks). Notice the this.fireEvent('afterBark') bit in the Dog class above? Check it out:
var killer = new Dog('Killer');
killer.addEvent('afterBark', function(dog){
alert(dog.name + ' just barked!');
});
killer.bark();
// ==> "My name is Killer and I am 5 years old"
// ==> "Killer just barked!"
It allows you to tie into the same event functionality used for the DOM, but with your own methods you create in your classes. I’m in love with this easy functionality — sure there’s been other ways to do this, but none so elegant as what the Moo team has come up with.
Chain
The last utility class is the Chain class. This allows for some nice chaining of classes: I’ll leave it up to you to explore this one since I haven’t used it in great detail yet. In a nutshell: it allows for time-dependent chains (so that events fire after another one is complete).
Conclusion
Every good Javascript developer knows that there’s 50 ways to skin a cat when it comes to classes and Javascript. But for me, one of the largest reasons MooTools is my framework of choice is the underlying class system. No extending Object, and no overriding of parent methods. The syntax is clean and easy to remember, giving it huge bonus points in my book.
Personally, I would like to thank the smarter developers who have taken the hard hits with Javascript to implement these nice OO techniques. Without them, my Javascript would still be procedural-based with tons of global variables thrown about. Yay for frameworks!
8 Comments
Make a Comment
don’t be afraid, it’s just text

Warpspire is the place that web professional Kyle Neath writes about the web. 



July 17th | #
I’d hardly consider it a blunder that JavaScript doesn’t have true class inheritance. Sure, plenty of people have come up with ways to solve “the problem” but I almost never require complex deep inheritance.
The Prototype/Mootools “mixin” approach, though, is very handy but even then, i mostly use it for class options and not for any kind of inheritance.
July 17th | #
I use a technique I learned from the Ext JS library. Here’s a live sample of one of the most complex declarations I use:
JR.Widget.TextField = function(h){
JR.Widget.TextField.superclass.constructor.call(this);
this.mixinittextfieldlabel();
this.mergeconf({
cls: ‘jr-textfield’,
textrange: null, // msie
size: 20
},h);
if (this.gut.place){
this.set_place(this.gut.place);
}
};
JR.mix(JR.Widget.TextField, JR.Widget.Common,
JR.Widget.CommonValidation, CommonTextFieldDataValue,
CommonTextFieldLabel, {
set_place: function(s, conf){
[snip]
}
[snip]
}
It’s single-inheritance with mixin support as well. It has scaled to tens of classes. Way cool and even uses namespace (JR) which is non-intrusive.
July 17th | #
Jonathan: I think it relies a lot on the person’s programming style. Personally, the more involved I get with Rails and ActionScript, the more OO-at-heart I become with my Javascript. Now I can’t seem to do anything without a Class or thinking it’s a dirty approach ;)
July 20 | #
javascript doesn’t have true classes because it’s not supposed to. it’s a prototyping language, and from my understanding on these types of languages, it’s just a matter of design.
think if prototyping could really work in a more traditional OO language? (i guess ruby can rename and eval functions to attach to a class at runtime, but i don’t have enough experience to know if changes to a class reflect to any current instances.)
but yeah, no blunder at all. it’s pretty amazing, actually, that you should even be able to emulate typical class functionality.
July 22nd | #
kaiser: Then my question for you is how did ECMAScript evolve into a fully strictly-typed object-oriented language if Javascript (based on ECMA) isn’t “supposed” to have classes? And if this is the case: why does ActionScript have classes? It serves essentially the same functionality as Javascript does but with a different interface (flash rather than the browser).
And one last point: if it’s not a blunder, why do so many libraries emulate classes? Just because something was done on purpose doesn’t mean it was done for the right reasons.
July 23rd | #
good questions, and i don’t knot if my answers will be accurate, but here’s my stab at:
“Just because something was done on purpose doesn’t mean it was done for the right reasons” — absolutely true, except that you’re missing the point of prototype languages. wikipedia gives a good description of one, but a fundamental idea is that there are no classes.
it seems, then, Ecma International made a conscious decision to base the standard on a prototype framework. no blunder — design decision. there are probably a lot of things in the background that lend prototyping to be better suited for client-side implementation on a variety of platforms. (take a walk to the other extreme, java. how fast do pages load with an applet? what type of beast would that be for anyone to do casual/quick scripting?)
the reason people are throwing in class emulation is really simple, in my view: what popular server-side languages are prototyping languages? fundamentally, none. they all have some class-based OOP. so it makes sense that people will want to continue working in a paradigm they’re comfortable with (or open up the doors for others to dig into javascript without having to fully understand prototyping, closures, etc.).
having said that, ecma-262 (4th edition) looks like it’ll be bending to popular usage, since it will support classes, packages, and namespaces (though I’m confused how namespaces will function if that ability is pretty much there, syntactically at least). but there’s no mention that they’re ditching the prototyping foundation, so all the syntax support for classes will no doubt function similar to how mootools handles it. syntactic sugar, basically.
the current actionscript is just a different beast for the reasons i just said in the latter paragraph, namely, using ecma-262 4th edition as its core. so it should be expected to be dramatically different than firefox’s javascript. but it’d be interesting to see a direct real-life comparison between the two and what’s functionally different from 3rd and 4th edition when you strip out the type-checking?
(i also think javascript is going to lose appeal when people have to adhere to strongly typed declarations for a language that never had it. it’s annoying for me, anyway. doesn’t make sense, given the context it’s used in.)
November 8th | #
[...] have, especially since I’ve started working Mootools classes and combining them with anonymous functions. The problem which Peter-Paul Koch explains very [...]
January 12th | #
[...] Warpspire: Mootools Javascript classes Related postsMootools - Automatically add SmoothScroll (0) [...]