Last active
August 29, 2015 14:21
-
-
Save ehsanullahjan/601b1046de76651d4e8a to your computer and use it in GitHub Desktop.
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
"use strict"; | |
// Base Girl object. | |
function Girl() { | |
this.name = ''; | |
this.traits = {}; | |
} | |
// Scout `is a` Girl | |
function Scout() { | |
Girl.call(this); | |
this.team = ''; | |
} | |
Scout.prototype = new Girl(); | |
Scout.prototype.constructor = Scout; | |
// Setup scout: Sarah | |
var sarah = new Scout(); | |
sarah.name = "Sarah"; | |
sarah.team = "Blue Scouts"; | |
sarah.traits.age = 30; | |
sarah.traits.weight = 125; | |
// Setup scout: Tricia | |
var tricia = new Scout(); | |
tricia.name = "Tricia"; | |
tricia.team = "Green Scouts"; | |
tricia.traits.age = 32; | |
tricia.traits.weight = 140; | |
// Log the girls | |
console.log("Sarah:", sarah, "\n"); | |
console.log("Tricia:", tricia, "\n"); | |
// Sarah (and Tricia) are both girl scouts | |
console.log(sarah instanceof Scout); | |
console.log(sarah instanceof Girl); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note lines #15 and #16:
If you set the
prototype
property of a constructor function, it "breaks" theconstructor
property of its instances (that you'll create in the future). As a reminder, in JavaScript all instances have aconstructor
property that point to the function that created it. For example:Now let's say you comment out line #16. Given the example above, it follows that
will output
[Function: Scout]
. However, it instead outputs[Function: Girl]
.That's because assigning
Scout.prototype
broke constructor property of its instances. To fix that, we need to remember to always setconstructor
property as shown in line #16 of the Gist.In summary the "native pattern" (as in what's followed in creation of JavaScript's native objects) for inheritance in JavaScript requires the following three steps:
prototype
of child to new instance of super (line #15).prototype.constructor
of child to child (line #16).