Skip to content

Instantly share code, notes, and snippets.

@ehsanullahjan
Last active August 29, 2015 14:21
Show Gist options
  • Save ehsanullahjan/601b1046de76651d4e8a to your computer and use it in GitHub Desktop.
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);
@ehsanullahjan
Copy link
Author

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.create since I believe the pattern shown above works perfectly and I'm not convinced Object.create() adds anything useful to the mix. Anyways, YMMW.

@ehsanullahjan
Copy link
Author

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:

  1. Remember to call super constructor function from the child constructor function (line #11).
  2. Set prototype of child to new instance of super (line #15).
  3. Set prototype.constructor of child to child (line #16).

@ehsanullahjan
Copy link
Author

A simple and clean example of this pattern can be seen here: http://bit.ly/1PESNli

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment