Skip to content

Instantly share code, notes, and snippets.

@quidmonkey
Last active December 18, 2015 02:29
Show Gist options
  • Save quidmonkey/5711170 to your computer and use it in GitHub Desktop.
Save quidmonkey/5711170 to your computer and use it in GitHub Desktop.
A simple Javascript inheritance example
Function.prototype.extends = function (parent) {
var ctor = function () {},
proto = this.prototype;
ctor.prototype = parent.prototype;
this.prototype = new ctor;
this.prototype.constructor = this;
for (var key in proto) {
this.prototype[key] = proto[key];
}
};
function foo () {};
foo.prototype = {
x: 5,
};
function bar () {};
bar.prototype = {
y: 6,
z: 7
};
// inherit!
bar.extends(foo);
var baz = new bar;
console.log(baz); // { x: 5, y: 6, z: 7 }
console.log(baz instanceof bar); // true
console.log(baz instanceof foo); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment