Skip to content

Instantly share code, notes, and snippets.

@xx7y7xx
Created March 29, 2016 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xx7y7xx/7b1e9f8bdb204865d83e to your computer and use it in GitHub Desktop.
Save xx7y7xx/7b1e9f8bdb204865d83e to your computer and use it in GitHub Desktop.
Method to setup inheritance
// http://stackoverflow.com/a/4389429
function extend(base, sub) {
// Avoid instantiating the base class just to setup inheritance
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
// for a polyfill
// Also, do a recursive merge of two prototypes, so we don't overwrite
// the existing prototype, but still maintain the inheritance chain
// Thanks to @ccnokes
var origProto = sub.prototype;
sub.prototype = Object.create(base.prototype);
for (var key in origProto) {
sub.prototype[key] = origProto[key];
}
// Remember the constructor property was set wrong, let's fix it
sub.prototype.constructor = sub;
// In ECMAScript5+ (all modern browsers), you can make the constructor property
// non-enumerable if you define it like this instead
Object.defineProperty(sub.prototype, 'constructor', {
enumerable: false,
value: sub
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment