Skip to Content
Learning JavaScript Design Patterns
book

Learning JavaScript Design Patterns

by Addy Osmani
July 2012
Intermediate to advanced content levelIntermediate to advanced
254 pages
6h 16m
English
O'Reilly Media, Inc.
Content preview from Learning JavaScript Design Patterns

Subclassing

For developers unfamiliar with subclassing, we will go through a brief beginners’ primer before diving into Mixins and Decorators further.

Subclassing is a term that refers to inheriting properties for a new object from a base or superclass object. In traditional object-oriented programming, a class B is able to extend another class A. Here we consider A a superclass and B a subclass of A. As such, all instances of B inherit the methods from A. B is however still able to define its own methods, including those that override methods originally defined by A.

Should B need to invoke a method in A that has been overridden, we refer to this as method chaining. Should B need to invoke the constructor A (the superclass), we call this constructor chaining.

To demonstrate subclassing, we first need a base object that can have new instances of itself created. Let’s model this around the concept of a person.

var Person =  function( firstName , lastName ){

  this.firstName = firstName;
  this.lastName =  lastName;
  this.gender = "male";

};

Next, we’ll want to specify a new class (object) that’s a subclass of the existing Person object. Let us imagine we want to add distinct properties to distinguish a Person from a Superhero while inheriting the properties of the Person superclass. As superheroes share many common traits with normal people (e.g. name, gender), this should hopefully illustrate how subclassing works adequately.

// a new instance of Person can then easily be created as follows: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Design Patterns - Second Edition

Mastering JavaScript Design Patterns - Second Edition

Simon Timms
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9781449334840Errata Page