DEV Community

hacker4world
hacker4world

Posted on

Add custom methods to Javascript built-in classes

Some people do not know this but you can actually add your own custom methods to strings, arrays and much more

Prototypes

As we know, every class in Javascript has a prototype containing all the methods that the instances of that class can use and we can access it using Class.prototype.

Adding methods to a prototype

Let's create a method called reverse to the String prototype that reverses the string:

String.prototype.reverse = function() {
    let rev = "";
    for (let i = 0; i < this.length; i++) {
        rev = this[i] + rev;
    }
    return rev;
}
Enter fullscreen mode Exit fullscreen mode

Now that will do the trick.
so the thing is that prototypes are also objects, and objects can have methods, so we attached the method reverse to the string prototype object, the this keyword inside the method will refer to the string we calling the method on.
now to use it we simply call it like any other method

console.log("Hello".reverse()); //olleH
Enter fullscreen mode Exit fullscreen mode

Now i don't know how would this be useful but i thought it's a cool thing to know!

Top comments (0)