links for 2008-04-19
April 19th, 2008 by James CarrWhat Happens When You Drop an HTC Mogul
April 14th, 2008 by James Carr
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-
Something all javascript developers should know.
Adding New Methods To Existing Javascript Objects
April 11th, 2008 by James CarrTaking 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-09
April 9th, 2008 by James Carr-
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.







