Last active
July 6, 2017 00:33
-
-
Save davedub/7940620 to your computer and use it in GitHub Desktop.
Prototype model of inheritance in Javascript
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
/* | |
"In JavaScript, a prototype is a property of functions and of objects that are created by constructor functions. | |
The prototype of a function is an object. Its main use is when a function is used as a constructor." | |
http://msdn.microsoft.com/en-us/library/hh924508(v=vs.94).aspx | |
"Since Javascript doesn't exactly have sub-class objects, prototype is a useful workaround to make a "base class" | |
object of certain functions that act as objects." | |
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype | |
Here's a whimsical example ... | |
*/ | |
var Dog = function() { | |
this.canTalk = false; | |
this.greet = function() { | |
if (this.canTalk) { | |
console.log("Hi, I'm a talking dog named " + this.name); | |
} | |
}; | |
}; | |
var Breed = function(n, o) { | |
this.breedname = n; | |
this.origin = o; | |
}; | |
var welsh_springer = new Breed('Welsh Springer', 'Wales'); | |
var lab = new Breed('Labrador Retriever', 'Canada'); | |
Breed.prototype = new Dog(); | |
var Pet = function(n, a, g) { | |
this.petname = n; | |
this.age = a; | |
this.gender = g; | |
}; | |
Pet.prototype = new Breed(); | |
var Talking_Pet = function(canTalk) { | |
this.canTalk = true; | |
}; | |
Talking_Pet.prototype = new Breed(); | |
/* now see what happens */ | |
var ava = new Pet('Ava','9', 'female'); | |
ava.prototype = welsh_springer; | |
var jack = new Pet('Jack', '3', 'male'); | |
jack.prototype = lab; | |
var joe = new Talking_Pet(); | |
joe.name = 'Joe'; | |
console.log(ava); | |
console.log(jack); | |
console.log(ava.prototype); | |
joe.greet(); | |
/* | |
{ petname: 'Ava', | |
age: '9', | |
gender: 'female', | |
prototype: { breedname: 'Welsh Springer', origin: 'Wales' } } | |
{ petname: 'Jack', | |
age: '3', | |
gender: 'male', | |
prototype: { breedname: 'Labrador Retriever', origin: 'Canada' } } | |
{ breedname: 'Welsh Springer', origin: 'Wales' } | |
Hi, I'm a talking dog named Joe | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment