Skip to content

Instantly share code, notes, and snippets.

@xphere
Created December 11, 2012 16:30
Show Gist options
  • Save xphere/4260069 to your computer and use it in GitHub Desktop.
Save xphere/4260069 to your computer and use it in GitHub Desktop.
Inherit JS
// Makes fn inherit from parent class
// Allows "super" calls ONLY in the constructor via Class.parent(this, param1, param2, ...)
// Also allows to extend the prototype giving more arguments
function inherit(parent, fn) {
fn || (fn = function() { });
fn.prototype = Object.create(parent.prototype);
for (var i = 2; i < arguments.length; ++i) {
extend(fn.prototype, arguments[i]);
}
fn.prototype.constructor = fn;
fn.parent = parent.call.bind(parent);
return fn;
}
function Part(vendor, model) {
this.vendor = vendor;
this.model = model;
}
Part.prototype = {
getVendor: function() { return this.vendor },
getModel: function() { return this.model }
};
function Tire(vendor, model, speed) {
Tire.parent(this, vendor, model);
this.speed = speed;
}
inherit(Part, Tire, {
getSpeed: function() {
return this.speed;
}
});
var tire = new Tire('vendor', 'model', 100);
console.log(tire.getVendor(), tire.getModel(), tire.getSpeed());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment