Skip to content

Instantly share code, notes, and snippets.

@stefanlindbohm
Last active January 1, 2016 01:19
Show Gist options
  • Save stefanlindbohm/8071984 to your computer and use it in GitHub Desktop.
Save stefanlindbohm/8071984 to your computer and use it in GitHub Desktop.
Simple JavaScript class implementation with inheritance.
// Class implementation with inheritance.
//
// Creates a constructor function with all the properties of ``params`` and
// keeps the ``constructor`` property of the prototype intact.
//
// Chains the object of special ``params`` key ``Extends`` on the prototype
// and prevents multiple calls to initialize in a MooTools Class compatible
// way. Property ``parent`` of the prototype is set to the chained object.
var Class = function(params) {
this.createConstructor();
if (params.hasOwnProperty("Extends")) {
this.extend(params.Extends);
delete params.Extends;
}
this.implement(params);
return this.constructor;
};
Class.prototype.createConstructor = function() {
var constructor = this.constructor = function() {
if (constructor.$prototyping) return undefined;
return this.initialize ? this.initialize.apply(this, arguments) : undefined;
}
};
Class.prototype.extend = function(parent) {
parent.$prototyping = true;
this.constructor.prototype = new parent();
delete parent.$prototyping;
this.constructor.prototype.constructor = this.constructor;
this.constructor.prototype.parent = parent;
};
Class.prototype.implement = function(params) {
for (var k in params) {
this.constructor.prototype[k] = params[k];
}
};
var Thing = new Class({
initialize: function(name) {
this.name = name;
},
describe: function() {
console.log(this.name);
}
});
var SpecialThing = new Class({
Extends: Thing,
describe: function() {
console.log(this.name + ", but special");
}
});
console.log(Thing.prototype); // Object with 'constructor' property intact
console.log(SpecialThing.prototype); // Object with Thing as prototype and 'parent' property pointing to it
var thing = new Thing("Anything");
thing.describe(); // Logs: 'Anything'
var specialthing = new SpecialThing("Something"); // 'initialize' is called just on object creation, not when prototyping
specialthing.describe(); // Logs: 'Something, but special'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment