links for 2008-04-19

April 19th, 2008 by James Carr

links for 2008-04-18

April 18th, 2008 by James Carr

What Happens When You Drop an HTC Mogul

April 14th, 2008 by James Carr

My Broken Phone

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

links for 2008-04-14

April 14th, 2008 by James Carr

links for 2008-04-13

April 13th, 2008 by James Carr

Adding New Methods To Existing Javascript Objects

April 11th, 2008 by James Carr

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. ;)

links for 2008-04-11

April 11th, 2008 by James Carr

links for 2008-04-09

April 9th, 2008 by James Carr

links for 2008-04-08

April 8th, 2008 by James Carr

April Fools!

April 2nd, 2008 by James Carr

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. ;)