Add Function to Prototype with Javascript

A

In some of my more recent posts about How to compare arrays in Javascript and Format Numbers as Currency with Javascript I have been enjoying adding them as extension methods to simplify their usage.

Honestly, I’ve always been afraid to do it because it seems “hard”. Now that I’ve done it once though, it is now becoming second nature. I really can’t believe I haven’t done this before because I absolutely love adding string extensions when I developer with C#.

Let’s take a look at some code to add a function with prototype using Javascript. In this first example I will add it to the Javascript Array Prototype:

[code]
// Extend the Array property
Array.prototype.equals = function (array2) {

if (!this || !array2)
return false;

if (this.length !== array2.length)
return false;

var array1Sorted = this.slice().sort();
var array2Sorted = array2.slice().sort();

return array1Sorted.every(function(value, index) {
return value === array2Sorted[index];
});

}
[/code]

The concept for Number is the exact same, you simply replace Array with Number as in the following example. I could see this being used in conjunction with the JavaScript String concat() Method

[code]
// Extend the number property
Number.prototype.currency = function(locale, isoCode) {
var formatter = new Intl.NumberFormat(locale, { style: ‘currency’, currency: isoCode });

return formatter.format(this);
}
[/code]

Hopefully with these two examples this will now become second nature to your Javascript code as it is quickly becoming mine!

About the author

By Jamie

My Books