Last active
October 27, 2015 17:05
-
-
Save nuweb/b3bacf99d954ce2f92cd to your computer and use it in GitHub Desktop.
Setting up prototypal inheritance in JavaScript
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
var Animal = { | |
type: 'mammal', | |
legs: 4, | |
eyes: ['blue', 'black', 'brown'], | |
saying: '' | |
}; | |
console.log(Animal.constructor); // Refers to the constructor method on the Object | |
Animal.prototype = { | |
constructor: Animal, // Reset the constructor on the child (of Object class) literal | |
say: function() { | |
console.log(this.saying); | |
} | |
}; | |
var Cat = Object.create(Animal); | |
var Dog = Object.create(Animal); | |
console.log(Object.keys(Cat)); // = [], empty because Cat only has inherited props, | |
console.log(Object.keys(Object.getPrototypeOf(Cat))); | |
console.log(Object.keys(Cat.__proto__)); | |
Cat.saying = 'meow'; | |
Cat.say = function() { // Overwrites inherited Animal say method | |
Animal.prototype.say.apply(this, Array.prototype.slice(arguments)); | |
}; | |
Cat.say(); // logs meow | |
console.log(Cat.legs); // logs 4 | |
Cat.eyes[0] = 'grey'; // mutating the inherited mutable props are mutated across all instances | |
console.log(Dog.eyes[0]); // grey | |
Cat.eyes = ['green']; // replacing the inherited mutable props are overriden for specific instance | |
console.log(Dog.eyes[0]); // still grey | |
console.log(Cat.eyes[0]); // green | |
// console.log(Cat.prototype.ears); | |
// Whatever is defined in the parent Object literal (Super class) prototype is available as Child object literal's (Sub class) prototype. If the S | |
// Whatever is defined on the parent Object literal (Super class) is available on the child Object literal (via parent's prototype) created with Object.create |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment