I would to extend the functionality of a JavaScript class, for example, to add utility functions to a specific Object.
Object.prototype
The prototype property can be used to add new properties and functions to any object, including built-in objects. For example, you could extend an Array as follows:
//
// extend Array objects, test if value is in array
// e.g., [0,1,2].contains(2) == true
// [0,1,2].contains('spam') == false
Array.prototype.contains = function(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] == obj) {
return true;
}
}
return false;
}
This will add the contains() function to all Array objects, even those already instantiated. The prototype property can be used to dynamically add new properties to all objects of a specific type, for example:
function Spam(name, eggs) {
this.name = name;
this.eggs = eggs;
}
function Foo(eggs) {
this.eggs = eggs;
}
myspam = new Spam('Brian', 12);
myfoo = new Foo(36);
function eggsByDozen() {
return this.eggs / 12;
}
Spam.prototype.dozens = eggsByDozen;
Foo.prototype.dozens = eggsByDozen;
myspam.dozens() // returns 1
myfoo.dozens() // returns 3
In this case, an existing function eggsByDozen() is applied to multiple classes, new objects and even previously instantiated objects of those types will have the new method.