Last active
December 18, 2015 02:29
-
-
Save quidmonkey/5711170 to your computer and use it in GitHub Desktop.
A simple Javascript inheritance example
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.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