Created
March 6, 2014 16:23
-
-
Save ecasilla/9393382 to your computer and use it in GitHub Desktop.
Js Inhertiance
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
Inheritance | |
Inheritance allows a class of objects to inherit the properties of another class. | |
Lets say for example we want to have a Parent and Child classes. We want the Child class to inherit from Parent. | |
function Parent() {}; | |
Parent.prototype.name = 'Parent'; | |
function Child() { | |
Parent.call(this); // We have to explicitly call the super class constructor. | |
// ... | |
} | |
// First we make the Child prototype a copy of the Parent prototype | |
Child.prototype = Object.create(Parent.prototype) | |
// You could also do: Child.prototype = new Parent() | |
// Next we make sure to reset the constructor, since this was overridden when we copied the prototype from the Parent. | |
Child.prototype.constructor = Child | |
// All instances of Child will now inherit from the prototype properties of Parent. | |
var child = new Child() | |
child.name === 'Parent' // The name property has been inherited from Parent. | |
// Still, we can override the property. | |
Child.prototype.name = 'Child' | |
child.name === 'Child' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment