Created
October 4, 2012 14:28
-
-
Save mheadd/3833864 to your computer and use it in GitHub Desktop.
Quick and dirty summary of prototypical inheritance in JS
This file contains hidden or 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
| // Create a Car object with doors. | |
| function Car() { | |
| this.doors = 4; | |
| }; | |
| // Method to return model year. | |
| Car.prototype.getYear = function(n) { | |
| var num = typeof(n) == 'undefined' ? 1 : n; | |
| return 2001 + num; | |
| }; | |
| // Hyundai class inherits from Car using standard prototypical inheritance. | |
| function hyundai(){} | |
| hyundai.prototype = new Car(); | |
| hyundai.color = 'red'; | |
| // Since inheritance created new object instance, we can access value set in constructor. | |
| console.log('Hyundai doors: ' + hyundai.prototype.doors); | |
| console.log('Hyundai color: ' + hyundai.color); | |
| console.log('Hyundai year: ' + hyundai.prototype.getYear() + '\n'); | |
| // Tesla class inherets using Node.js style prototypical inheritance. | |
| function tesla(){} | |
| tesla.prototype.__proto__ = Car.prototype; | |
| tesla.color = 'blue'; | |
| // Since object not instantiated with inheritance, no access to values set in constructor. | |
| console.log('Tesla doors: ' + tesla.prototype.doors); | |
| console.log('Tesla color: ' + tesla.color); | |
| console.log('Tesla year: ' + (tesla.prototype.getYear(10))); | |
| /* | |
| Outputs: | |
| Hyundai doors: 4 | |
| Hyundai color: red | |
| Hyundai year: 2002 | |
| Tesla doors: undefined | |
| Tesla color: blue | |
| Tesla year: 2011 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment