Extending JavaScript Objects and Classes

Recently I was working on a project where I was working with dates in JavaScript, and found myself needing to output the dates as numbers with leading zeros. Since I had multiple places in my code where I needed to add the leading zeros, I decided to extend the JavaScript Number object rather than just making some inline logic that would be repeated in multiple places.

Now if you’re familiar with JavaScript, you know that extending a JavaScript object is nothing new. Regardless, the code snippet below shows how to add a custom function to a built-in JavaScript object using the Object.prototype property.

Number.prototype.addLeadingZero = function() {
  return (this > 9) ? String(this) : "0" + this;
};
// Sample usage
var myNum = 9;
console.log(myNum.addLeadingZero()); // Outputs "09"

Note that in the code snippet above, my addLeadingZero method always returns a String, rather than a Number, even if a leading zero isn’t added. This was intentional for my purposes, and necessary for returning a number with a leading zero.

If you find yourself needing to extend a JavaScript object, you can use simply use the Object.prototype property, and add in your own custom method(s). This makes your custom method accessible on the specified object type (Number, in my example above).

Until next time, happy coding!

There are no comments yet, add one below.

Leave a Comment