Here is my take on it to provide it in a more simplest way.
What is Inheritance?
Inheritance as in java is to extend a abstract or parent class to acquire all the properties of the parent to the child with addition or change of any specific properties if needed.
How can we implement this in javascript?
In general, people used to overwrite any specific method or to add any new method to the existing dom object. For this purpose, in javascript we tend to use the keyword "prototype".
For eg, if you are about to add a method to String object in the dom. Then you have to follow the following steps:
Note: String is the intrinsic object available in the dom, which doesn't have trim functionality by default. Here we are about to implement the trim functionality to the "String" object.
String.prototype.trim = function() {
var x = this;
x = x.replace(/^\s*(.*)/, "$1");
x = x.replace(/(.*?)\s*$/, "$1");
return x;
}
In the above example, we are extending the intrinsic dom object "String" to add one more function "trim" using the property "prototype".
One more example for better understanding, suppose if you want email check and to be enclosed in the intrinsic String object, then you can write it in the following way:
String.prototype.isEmail = function() {
var emailRegExp = /^[a-z0-9]([a-z0-9_\-\.]*)@([a-z0-9_\-\.]*)(\.[a-z]{2,3}(\.[a-z]{2}){0,2})$/i;
return emailRegExp.test(this);
}
And some of the other intrinsic dom objects which exposes their "prototype" property were
Array, Boolean, Date, Function, Number, Object and RegExp.
Experiment and enjoy as much.If you want more explanation and examples then do have a look at the following url: http://www.codeproject.com/KB/scripting/prototypes.aspx
In the next post, i will be analyzing about the same topic with different approach.
