Add Function to Prototype with Javascript Add Function to Prototype with Javascript

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:



// 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];
});
}

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


// Extend the number property
Number.prototype.currency = function(locale, isoCode) {
var formatter = new Intl.NumberFormat(locale, { style: 'currency', currency: isoCode });
return formatter.format(this);
}

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

Published on Jun 26, 2022

Tags: JavaScript | jQuery Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.