-
-
Save ehsanullahjan/601b1046de76651d4e8a to your computer and use it in GitHub Desktop.
| "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); |
Note lines #15 and #16:
Scout.prototype = new Girl();
Scout.prototype.constructor = Scout;If you set the prototype property of a constructor function, it "breaks" the constructor property of its instances (that you'll create in the future). As a reminder, in JavaScript all instances have a constructor property that point to the function that created it. For example:
console.log((5).constructor); // logs [Function: Number]Now let's say you comment out line #16. Given the example above, it follows that
console.log(sarah.constructor);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 set constructor 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:
- Remember to call super constructor function from the child constructor function (line #11).
- Set
prototypeof child to new instance of super (line #15). - Set
prototype.constructorof child to child (line #16).
A simple and clean example of this pattern can be seen here: http://bit.ly/1PESNli
There's a gotcha the pattern shown in the gist fixes. You'd do yourself a favor by reading http://bit.ly/1FM2nyb. For good measure, check out http://bit.ly/1KdLXwb as well.
I personally do not like
Object.createsince I believe the pattern shown above works perfectly and I'm not convincedObject.create()adds anything useful to the mix. Anyways, YMMW.