Introduction
The aim of the tip is to explore a simple inheritance example in JavaScript. Yes, there are quite a good number of options to follow, but this solution worked fine for me.
Background
I have been working with JavaScript for a short period of time. By this time, I have been in a situation where the same code segment was repeated again and again. So I needed a way to reform them to reduce the code and centralize them. One option was to write the JQuery plugin. But using the normal function has not been the best option. I wanted to use inheritance as I do in C#. So I started Googling, after exploring some solutions, I adopted a solution which helped me a lot.
Using the Code
We will start with a basic base object Math
which has the ability to find odds and evens from a given number array, using odds and evens prototypes.
function Math() { }
Math.prototype.odds = function(numberArray) {
return $.grep(numberArray, function(number) {
return number % 2 === 1;
});
};
Math.prototype.evens = function (numberArray) {
return $.grep(numberArray, function (number) {
return number % 2 === 0;
});
};
Before we move on to the child object Calculator
which will inherit from the base Math
object, we need a utility function to help use in inheritance. And it would be like this, which copies all the prototypes of a given object. And returns the new object.
function prototypeClone(baseObject) {
function baseClone() { }
baseClone.prototype = baseObject.prototype;
return new baseClone();
}
Now we are going to use this utility function with the child object Calculator
to inherit from the base object Math
like this. Reforming the prototype constructor is very important work to do, the last line:
function Calculator() { }
Calculator.prototype = prototypeClone(Math);
Calculator.prototype.constructor = Calculator;
After this inheritance, the child Calculator
object will be able to use odds, evens and all prototypes, which belong to the base object Math
. And we can add new ones too to the Calculator
object if we want to. Now test how the Calculator
object works.
$(document).ready(function () {
var calculator = new Calculator();
var odds = calculator.odds([1, 2, 3, 4, 5]);
var evens = calculator.evens([1, 2, 3, 4, 5, 6]);
alert(odds);
alert(evens);
});