Adding New Methods To Existing Javascript Objects
Taking a lunch break from training today and I thought it’d be good to illustrate something that’s pretty standard in javascript, but might be pretty new for some. One of my favorite features is the ability to add new methods to existing object prototypes. For example, wouldn’t it be neat to be able to have an array method that sums all of the elements in the array?
The normal approach might be something like the following:
function sum(collection){
var result = 0;
for(var i = 0; i < collection.length; i++){
result+= collection[i];
}
return result;
}
var a = [1,2,3,4];
alert(sum(a));
This would show an alert box with the value 10. Pretty simple. But what if we could do this?
alert([1,2,3,4].sum());
The answer… you can. All you need to do is add the sum method to the prototype of Array, which will make any new instance of array have the new method:
Array.prototype.sum = function(){
var result = 0;
for(var i = 0; i < this.length; i++){
result+= this[i];
}
return result;
}
That does it. But what if we only want one array, not all arrays, to have a sum method? you can still do this by adding it to the actual object (this is where prototypes come into play):
var a = [1,2,3,4];
a.sum = function(){
var result = 0;
for(var i = 0; i < this.length; i++){
result+= this[i];
}
return result;
}
alert(a.sum()); // prints 10
alert([1,2,3,4].sum()); // runtime error... object does not support this property
Hope that provides a good illustration of how to add new methods to existing object prototypes in javascript, as well as illustrate the distinction between objects and object prototypes. As an exercise for the reader, make the preceding examples work even if the collection contains non-numeric items.
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!







