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.