Java Reference
In-Depth Information
Adding Methods to Built-in Objects
It is possible to add more methods to the prototype of JavaScript's built-in objects—such
as Number , String , and Array —to add more functionality. This practice is known as
monkey-patching , but it is mostly frowned upon in the JavaScript community, despite it
being an incredibly powerful technique [6] .
As an example, we can add isOdd() and isEven() methods to the Number wrapper
object's prototype. These methods will then be available to number primitives:
Number.prototype.isEven = function() {
return this%2 === 0;
Number.prototype.isOdd = function() {
return this%2 === 1;
We can try a few more examples to check that these work:
<< true
<< false
Arrays are powerful objects, but seem to have some basic methods missing in JavaScript
that are found in other languages. We can add a first() and last() methods that return
the first and last items in the array:
Array.prototype.first = function() {
return this[0];
Array.prototype.last = function() {
Search WWH ::

Custom Search