Book Image

Object-Oriented JavaScript

Book Image

Object-Oriented JavaScript

Overview of this book

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

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.prototype.name = 'shape';
Shape.prototype.toString = function() {return this.name;};

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