Skip to content

Instantly share code, notes, and snippets.

@dmikis
Last active December 19, 2015 13:58
Show Gist options
  • Save dmikis/5965474 to your computer and use it in GitHub Desktop.
Save dmikis/5965474 to your computer and use it in GitHub Desktop.
Proper inherit
function inherit(base, props, statics) {
if (typeof base !== 'function') {
statics = props;
props = base;
base = Object;
}
props.constructor.prototype = Object.create(base.prototype);
Object.keys(props).forEach(function (prop) {
props.constructor.prototype[prop] = props[prop];
});
props.constructor.prototype.superproto = base.prototype;
if (statics) {
Object.keys(statics).forEach(function (prop) {
if (prop !== 'prototype') {
props.constructor[prop] = statics[prop];
}
});
}
props.constructor.
return props.constructor;
}
var A = inherit({
foo: function () {
return 1;
}
});
var B = inherit(A, {
foo: function () {
return this.superproto.foo.call(this) + 1;
},
answer: function () {
return 42;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment