Tuesday 22 January 2013

JavaScript Inheritance In 6 Basic Steps


 
// Define Base Class
function BaseClass() { } 

// Define a Function
BaseClass.prototype.SomeFunction = function () { alert("Base Class SomeFunction"); } 

// Define Child Class
function ChildClass() {
    BaseClass.call(this); // Call the Parent Constructor
}

// Specify that the ChildClass Inherits from the base class
ChildClass.prototype = new BaseClass(); 

// Ensure that the Child Class constructor points to itself & not the Base Class
ChildClass.prototype.constructor = ChildClass;

// Override the "SomeFunction" from the Base Class
ChildClass.prototype.SomeFunction = function () { alert("Child Class SomeFunction"); }

Now we can create an instance of the Child class like so ..
 
// Create an instance of the ChildClass
var object = new ChildClass();
And now, a call to the "SomeFunction" returns the overriden implementation.
 
// Call the "SomeFunction" method.
object.SomeFunction(); // This returns an alert containing: "Child Class SomeFunction"

References: Introduction to Object-Oriented JavaScript

No comments:

Post a Comment