James Carr | Rants and Musings of an Agile Developer

Archive for April 2008

Apr/08

19

links for 2008-04-19

Apr/08

18

links for 2008-04-18

My Broken Phone

Thankfully I pay five dollars extra a month for insurance. It’s already replaced, just got the image up late. ;)

No tags

Apr/08

14

links for 2008-04-14

No tags

Apr/08

13

links for 2008-04-13

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

Apr/08

11

links for 2008-04-11

Apr/08

9

links for 2008-04-09

No tags

Apr/08

8

links for 2008-04-08

Apr/08

2

April Fools!

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

Older posts >>

Theme Design by devolux.nh2.me