Normally, there's an ad running in this spot, but you're using an ad blocker. To help support our blog, which provides free tutorials for everybody, we just ask that you whitelist or follow us on facebook, twitter, or subscribe using the form to the leftabove. Thank you!

    Prototypal Inheritance with Javascript

    The Prototype Chain

    As a class-free, object oriented language, JavaScript affords a few different methods for achieving inheritance. Coming from ActionScript 3, myself, I found myself wanting to leverage a style closer to a class-based inheritance model, but there's a reason prototype is the Douglas Crockford endorsed standard. By the way, his book, JavaScript: The Good Parts, is a must read for all JavaScript programmers. Douglas Crockford is JavaScript.

    Anyway, let's jump right into it. Prototype is basically the shared properties that all JavaScript objects inherit from the same base object. Here's an example:

    Prototypal Inheritance

    The following block of code demonstrates Douglas Crockford's prototypal inheritance operator, in which the OldObject is added to the NewObject's prototype, inheriting all of it's public properties and methods. Keep in mind that with this pure prototypal pattern you are to use plain objects, not functions. No initialization needed.

    Classical Inheritance

    The following example tries to follow a more class-based style of inheritance by attaching Vehicle's prototype to Motorcycle and allowing you to overwrite the constructor. In case you're not sure what a constructor is in terms of JavaScript functions, it's essentially everything that executes within the scope the main function. So in the following example, everything within the scope of Vehicle, but not within the scope of this.go() fires.

    Now that we've declared Vehicle, Motorcycle may inherit from it. Motorcycle's constructor contains a call to Vehicle's constructor through apply, and then adds any overrides or custom properties and functions thereafter. In this case, a motorcycle only has two wheels and one headlight.

    So there it is. If you're interested in learning about another way to implement inheritance in JavaScript, make sure to also check out John Resig's approach. Also, check out this article to get a deeper understanding of call and apply.

    For a deeper understanding of design patterns, Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series) is the best book you could possibly own.

    Did you like this tutorial? Help us pay for server costs by following us on Facebook, Twitter, and subscribing below, where you'll get post notifications, training webinar invites, and free bundles.