Archive for April 2008

Thankfully I pay five dollars extra a month for insurance. It’s already replaced, just got the image up late.
No tags
-
Something all javascript developers should know.
No tags
No tags
11
Adding New Methods To Existing Javascript Objects
No comments · Posted by James Carr in Javascript, Uncategorized
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.
No tags
No tags
-
Looks like there’s something new to develop web applications on.
-
Just came across concordion today (thanks to Adam England) and it looks pretty interesting for writing executable requirements.
No tags
No tags
Okay, so I lied… I didn’t really move to Portland. In fact, the “view from my loft balcony” is really just a pic I snapped from the Oregon Convention Center back in 2006 when I attended OOPSLA there. So no biggie.. I’m still in Columbia.
No tags
