How to use extensive functions in Javascript

Asked

Viewed 88 times

0

In Javascript primitive types have native functions, such as an object of the type Number has a function toString():

(1).toString(); // "1"

And an array has a includes():

[1, 3, 4].includes(1); // true
[1, 3, 4].includes(10); // false

I wish I could create a native method for arrays that returns me true whether it contains at least an odd number, and false if it only has even numbers:

[8, 2, 4].hasOdd(); // true 
[1, 2, 4].hasOdd(); // false

Is there any way I can create a method that serves for a certain type of object in Javascript, such as extensive functions in Kotlin?

2 answers

2


What you’re looking for is the prototype:

All javascript objects have ineter methods from your prototype, so if you want to use extensive functions, you can do something like this:

String.prototype.hello = function() {
    return `Hello, ${this}`;
}

Then using as follows:

"World".hello(); // "Hello, World"

Just as you can modify the prototype of String, you have the freedom to do the same with the prototype of Array:

Array.prototype.plusOne = function() { 
    return this.map((e) => e + 1);
}

Using the following way:

[10, 3, 5].plusOne(); // [11, 4, 6]

The resolution of the problem:

If your idea is to create a native method for arrays that returns me true whether it contains at least an odd number, and false if this has only even numbers, you can do so:

Array.prototype.hasOdd = function() {
    return this.every((e) => e % 2 === 0);
}

Using the following way:

[2, 2, 2].hasOdd(); // false
[1, 2, 2].hasOdd(); // true

You should use extensive functions with prototype?

It depends, the w3schools does not recommend that you modify the prototypes of native Javascript objects, you in theory should only modify prototypes of your objects.

As you are adding a new method and not overwriting an old one, I believe there is no problem, example: You should not overwrite the method toString() of the prototype of Number, this can create side effects in your code.

Only Modify your Own prototypes. Never Modify the prototypes of standard Javascript Objects.

1

In the early days of Web development this was a common practice, (Prototypejs and Sugar js.) are good examples.

The problem is to maintain the compatibility and interoperability of these library types, as collisions can easily occur. Another implicit problem is something that haunts jQuery to this day, not knowing that that method is not native, for the most unsuspecting can try to reproduce these behaviors in other projects, and fail miserably.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.