Created
December 11, 2012 16:30
-
-
Save xphere/4260069 to your computer and use it in GitHub Desktop.
Inherit JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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