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.