How to use extensive functions in Javascript

0

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

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

And an array has includes() :

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

I would like to be able to create a native method for arrays that returns me true if it contains at least an odd number and false if it has only even numbers:

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

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

    
asked by anonymous 28.01.2018 / 22:49

2 answers

2

What you are looking for is prototype :

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

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

Then use it 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]

Solving the problem:

If your idea is to create a native method for arrays that returns me true if it contains at least an odd number and false if it 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

Should you use extensive functions with prototype?

Depends on w3schools does not recommend that you modify the prototypes of native Javascript objects, you should in theory just modify prototypes of your objects.

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

  

Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.

    
28.01.2018 / 22:49
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 this type of library because there can easily be collisions. Another implicit problem is something that haunts jQuery to this day, not knowing that that method is not native, for the most unsuspecting ones can try to reproduce these behaviors in other projects, and fail miserably.

    
30.01.2018 / 13:20