Making an Extension Method in Javascript

In C# if a type does not have a built-in function/method we can create an Extension method and then an object of that type can call the Extension method using the dot operator as if it is a native or a built-in method of that type. Is there something similar to that in Javascript? If so can you please explain with an example.

Sure thing.

The querySelectorAll() method doesn’t support the map method.

That querySelectorAll() method returns its results as a NodeList collection, so we can add to its prototype the Array map method, and use that in our code.

NodeList.prototype.map = Array.prototype.map;

const divs = document.querySelectorAll("div");
const textContents = divs.map(div => div.textContent);
console.log(textContents);

See the example here:

Hi Paul, Thanks for your reply. Can this be done to any type? For example if I want to create a custom function that can be applied to any array to determine if a value exists between two indices of an array is this possible and if so will it have a negative impact to modify the array prototype as some people have said in stackoverflow? This function will take as inputs the array to search, the starting and ending indices where you want to start and stop the search, the number you’re searching for in the array, and it will return a Boolean value.

If it’s for your own use, then you can do what you like and I would say experimentation is a good thing.

As far as good practice I would say it is probably a bad idea to create custom methods on built-ins. One it’s confusing and two if a method of the same name is implemented as an official Javascript method you are going to run into conflicts down the line. Funnily enough there used to be a framework called prototype that if I remember correctly was built on this premise.

It is just as easy to just write a standard function to do the job, and if chaining is desired then there are ways to do that too.

This might be of interest to you though. It is a list of proposals for upcoming ECMA script releases.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.