Skip to content

Instantly share code, notes, and snippets.

@harmesy
Created April 16, 2013 20:47
Show Gist options
  • Save harmesy/5399504 to your computer and use it in GitHub Desktop.
Save harmesy/5399504 to your computer and use it in GitHub Desktop.
Quasi-class structure in JS. Allows for inheritance.
var Class = function() {
var klass = function() {
this.init.apply(this, arguments);
}
// provide access to parent
//klass.prototype.parent = klass;
// called if the inheriting class doesn't override
klass.prototype.init = function() { };
// class methods
klass.extend = function(obj) {
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
this[i] = obj[i];
}
}
};
// instance methods
klass.include = function(obj) {
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
this.prototype[i] = obj[i];
}
}
};
/* --------------------------------------
# Sets up a new class with this class
# as the inheriting class.
-------------------------------------- */
klass.inherits = function() {
var F = function() {
this.init.apply(this, arguments);
};
// copy the class methods in
for(var i in this) {
if(this.hasOwnProperty(i)) {
F[i] = this[i];
}
}
// copy the instance methods in
// we can't just set the prototype to this.prototype because if they share an object
// then when we add properties to the subclass it'll also exist in the prototype
// of the superclass.
// Also, we don't want to use hasOwnProperty because we want to inherit all of
// the properties above.
for(var i in this.prototype) {
F.prototype[i] = this.prototype[i];
}
return F;
};
return klass;
};
var Big = new Class;
Big.extend({
bigClassMethod: function() {
return "Big class method";
}
});
Big.include({
bigInstanceMethod: function() {
return "Big instance method";
}
});
var Little = Big.inherits();
Little.extend({
littleClassMethod: function() {
return "Little class method";
}
});
Little.include({
littleInstanceMethod: function() {
return "Little instance method";
}
});
var Tiny = Little.inherits();
Tiny.extend({
tinyClassMethod: function() {
return "Tiny instance method";
}
});
Tiny.include({
tinyInstanceMethod: function() {
return "Tiny instance method";
}
});
var myBig = new Big();
var myLittle = new Little();
var myTiny = new Tiny();
console.log("### Big stuff ###")
console.log(Big.bigClassMethod());
console.log(myBig.bigInstanceMethod());
console.log("\n### Little stuff ###");
console.log(Little.bigClassMethod());
console.log(Little.littleClassMethod());
console.log(myLittle.bigInstanceMethod());
console.log(myLittle.littleInstanceMethod());
console.log("\n### Tiny stuff ###");
console.log(Tiny.bigClassMethod());
console.log(Tiny.littleClassMethod());
console.log(Tiny.tinyClassMethod());
console.log(myTiny.bigInstanceMethod());
console.log(myTiny.littleInstanceMethod());
console.log(myTiny.tinyInstanceMethod());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment