In order to write elegant JS code, the first thing we needed was to set up a framework for object-oriented programming. A lot of what we need is already built into the JavaScript language, which is a fully object-oriented language. But we wanted to sidestep some of the pitfalls of standard inheritance patterns while adding some extra features.
We started with this class inheritance framework by John Resig, which gave us the ability to write beautiful code like this example from Resig:
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
},
dance: function(){
return this.dancing;
}
});
var Ninja = Person.extend({
init: function(){
this._super( false );
},
dance: function(){
// Call the inherited version of dance()
return this._super();
},
swingSword: function(){
return true;
}
});
var p = new Person(true);
p.dance(); // => true
var n = new Ninja();
n.dance(); // => false
n.swingSword(); // => true
// Should all be true
p instanceof Person && p instanceof Class &&
n instanceof Ninja && n instanceof Person && n instanceof Class
Resig’s framework is great, but we wanted some additional features in our Class implementation: