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

Inheriting the Prototype Only

As explained above, for reasons of efficiency you should consider adding the reusable properties and methods to the prototype. If you do so, then it's probably a good idea to inherit only the prototype, because all the reusable code is there. This means that inheriting the object contained in Shape.prototype is better than inheriting the object created with new Shape(). After all, new Shape() will only give you own shape properties which are not meant to be reused (otherwise they would be in the prototype). You gain a little more efficiency by:

  • Not creating a new object for the sake of inheritance alone, and

  • Having less lookups during runtime when it comes to searching for toString() for example.

Here's the updated code; the changes are highlighted:

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

function TwoDShape(){}
// take care of inheritance
TwoDShape.prototype = Shape.prototype...