OOP inheritance in JavaScript

JavaScript programs are usually small and built to solve very specific issues in a web page. Recently I needed to go one step beyond the order of small. I needed to write a JavaScript program just as I would write a similar one in any other language, i.e. using abstract and extended objects.

It is shocking how little information you can find about OOP inheritance in JavaScript. While searching I found this article by Mozilla explaining the bits of information I was missing. So here is a blog post that is practically advertising one advanced but very useful programming side of JavaScript.

The following example has a base class called "Father" and a class that extends it called "Son". A common method for both of them is fix_problems(), so here is how Son inherits from Father and how it redefines the common method.

// define Father class
function Father() {
    // Father constructor
}

// define Father's fix_problems() method
Father.prototype.fix_problems = function () {
    alert("Call wife");
}

// create Son class that inherits from Father
Son.prototype = new Father();

// correct Son's constructor - unless you do that, Son's constructor points to Father's constructor
Son.prototype.constructor = Son;

// define Son's version of the fix_problems() method
Son.prototype.fix_problems = function () {
    alert("Call mom");
}

// test
var bob = new Son();
bob.fix_problems(); // alerts: Call mom