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

Isolating the Inheritance Part into a Function

Let's move the code that takes care of all of the inheritance details into a reusable extend() function:

function extend(Child, Parent) {
  var F = function(){};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.uber = Parent.prototype;

Using this function (or your own custom version of it) will help you keep your code clean with regard to the repetitive inheritance-related tasks. This way you can inherit by simply using:

extend(TwoDShape, Shape);


extend(Triangle, TwoDShape);

This approach is the way the YUI (Yahoo! User Interface) library implements inheritance through its extend() method. For example, if you use YUI and you want your Triangle to inherit from Shape, you use:

YAHOO.lang.extend(Triangle, Shape)