Book Image

Object-Oriented JavaScript

By : Stoyan Stefanov, Stoyan STEFANOV
Book Image

Object-Oriented JavaScript

By: Stoyan Stefanov, Stoyan STEFANOV

Overview of this book

Table of Contents (18 chapters)
Object-Oriented JavaScript
About the Author
About the Reviewers
Built-in Functions
Regular Expressions

Borrowing a Constructor

O ne more way of implementing inheritance (the last one in the chapter, I promise) has to do again with constructor functions, and not the objects directly. In this pattern the constructor of the child calls the constructor of the parent using either of the call() or apply() methods. This can be called stealing a constructor, or borrowing a constructor if you want to be more subtle about it.

call() and apply() were discussed in Chapter 4, but here's a refresher: they allow you to call a function and pass an object that the function should bind to its this value. So for inheritance purposes, the child constructor calls the parent's constructor and binds child's newly-created this object as the parent's this.

Let's have this parent constructor Shape():

function Shape(id) { = id;
} = 'shape';
Shape.prototype.toString = function(){return;};

Now let's define Triangle() which uses apply() to call the Shape() constructor, passing this...