JavaScript Inheritance

by soulwire

JavaScript

/*

    basic example of inheritance in javascript

*/

// ----------
// Base class
// ----------

function Shape( name ) {
    this.name = name || 'shape';
}

Shape.prototype.doSomething = function() {
    console.log( 'doSomething() --> ' + this.name );
};

Shape.prototype.doSomethingElse = function() {
    console.log( 'Shape doing something else' );
};

// ----------
// Child class
// ----------

function Circle() {
    // some circle specific code in the constructor
    this.radius = 20;
}

// 'extend' shape by inheriting the prototype
Circle.prototype = new Shape( 'circle' );

// override a function on the super class
Circle.prototype.doSomethingElse = function() {
    
    // effectively call 'super'
    Shape.prototype.doSomethingElse.call( this );
    
    // circle specific stuff
    console.log( 'Circle radius:', this.radius );
};

// ----------
// Test
// ----------

console.log( '----- test shape' );

var shape = new Shape();
shape.doSomething();
shape.doSomethingElse();

console.log( '----- test circle' );

var circle = new Circle();
circle.doSomething();
circle.doSomethingElse();