Javascript Inheritance and the prototype chain
It is often required to extend existing object or class to add new methods or override existing methods. Almost All the Object Oriented Programming Languages provide this feature using inheritance.
Lets see how to achieve inheritance in prototype
based language like Javascript
. To understand more about prototypes in javascript follow the reference provided below.
In this example, lets override the parse
method of Date
object. The overriding parse method is going to use moment.js to parse the date instead of default.
Date.parse = function (date) {
var format = 'DD-MM-YYYY'
return moment(date, format).toDate();
};
The above method parses provided string date in specified format to Date
object. See the below output which has parsed the string date provided in DD-MM-YYYY
to Date object.
> Date.parse('08-12-1981')
< Tue Dec 08 1981 00:00:00 GMT+0530 (IST)
*In the above example we have seen how to override the existing parse
method of Date
object.
Now let see how to extend the Date
object using prototypes.
Date.prototype.isLessThan = function (toDate) {
var mToDate = Date.parse(toDate);
return (this.getTime() < mToDate.getTime());
};
In the above function isLessThan
is added to Date
instance using prototype.
Now we will see how to use both the methods defined above.
> Date.parse('01-12-1981').isLessThan('02-12-1981')
< true
For more details about javascript inheritance and prototype refer the link below from MDN.
References: