Skip to content

Instantly share code, notes, and snippets.

@Rhoxio
Last active September 23, 2016 20:26
Show Gist options
  • Save Rhoxio/dd5b88f010aa5338448d15267403ef33 to your computer and use it in GitHub Desktop.
Save Rhoxio/dd5b88f010aa5338448d15267403ef33 to your computer and use it in GitHub Desktop.

Inheritance in Javascript

You are walking down the street, thinking about how to best model reality through code in order to create the ultimate Pet Diet app, and you stumble across a conundrum. You have a model of a cat and a model of a dog. They are both animals and share similar properties with one another, but in order to model them in code, you'd have to re-write attributes like weight, age, dietRestrictions, and owner. While you could sit down and write out a new object for every pet type that comes your way, but there has to be a better way to share attributes and functionality between similar objects.

Both the dog and cat should be able to run, jump, play, hunt, eat and reproduce. But, can't most mammals do something similar? They have more baseline similarities than differences, and for the purposes of your app, they really only end up being different species with may more in common than they have differences.

This is where inheritance becomes a powerful tool for you to leverage. Inheritance allows you to share functionality and attributes across objects by 'inheriting' from a parent object. You can solve this pet conundrum more cleanly by just inheriting from a Mammal or Animal object!

When using inheritance in Javascript, it is important to note that it is not quite like what is refered to as 'classical inheritance' where you have a class structure (like in Ruby) linked directly to another class. In Javascript, you essentially end up reassigning attributes and objects to another object, effectively 'inheriting' it's traits.

To get started, go ahead and get yourself a copy of THIS gist. Save it as a .js file, and be prepared to run it with the 'node' command.

During this lesson you will learn:

  1. What inheritance is in Javascript.
  2. How inheritance can be leveraged to create robust and extensible objects.
  3. What a prototype is on a Javascript object.
  4. How to use .call() to inherit attributes from a parent object.
  5. How to assign a parent object's prototype to a child's prototype to inherit functionality.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment