Created
March 3, 2016 19:21
-
-
Save olitreadwell/69172d0591f3daef7fcc to your computer and use it in GitHub Desktop.
Basics of JavaScript Prototype-based Inheritance
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
// Construct a Canine object | |
var Canine = function(latinName) { | |
this.genus = "Canis"; | |
this.latinName = latinName; | |
} | |
// Create two distinct instances of the Canine object | |
var dog = new Canine("Canis familiaris"); | |
var greyWolf = new Canine("Canis lupus"); | |
// Add a howl() method to our Canine object | |
Canine.prototype.howl = function () { | |
console.log("AAAAWWWOOOOOO"); | |
} | |
// Show that both instances can howl(); | |
dog.howl(); | |
greyWolf.howl(); | |
// Add a fetch() method to our dog instance | |
dog.fetch = function() { | |
console.log("dog wants to play fetch!"); | |
} | |
dog.fetch(); | |
// Add a hunt() method to our greyWolf instance | |
greyWolf.hunt = function() { | |
console.log("grey wolf is hunting its prey"); | |
} | |
greyWolf.hunt(); | |
// Check to see that our instances haven't 'inherited' | |
// these newly created methods (they shouldn't) | |
// both of these should return TypeErrors | |
dog.hunt(); | |
greyWolf.fetch(); | |
// Create a new Dog object that inherits from our Canine object | |
// The Canine.call method allows us to set a value for | |
// latinName from within our new Dog object in the context | |
// of the Canine object | |
var Dog = function(name, latinName) { | |
Canine.call(this, latinName); | |
this.name = name; | |
} | |
// Create an instance of the Dog object | |
var spot = new Dog('Spot', 'Canis familiaris'); | |
// Can our new instance use the Canine method howl() ? | |
// As of now, No. | |
// The method call below will return a TypeError | |
spot.howl(); | |
// Make it so our Dog object inherits from the Canine object | |
// The Object.create call is the first part | |
// It creates a Dog.prototype object from the Canine.prototype object. | |
// Dog then inherits all the properties and methods from Canine. | |
Dog.prototype = Object.create(Canine.prototype); | |
// Set the Dog.prototype object' original constructor | |
// You need to do this each time you inherit | |
// Otherwise it would use the Canine constructor function | |
// Not the Dog constructor function | |
Dog.prototype.constructor = Dog; | |
// Our spot variable should now be able to howl() | |
spot.howl(); | |
// Make it so our Dog object can fetch() | |
Dog.prototype.fetch = function() { | |
console.log(this.name + ' wants to play fetch!'); | |
} | |
// Create a new Dog instance and try out fetch() | |
var clifford = new Dog('Clifford', 'Canis familiaris'); | |
clifford.fetch(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment