I have to admit a secret. I actually like JavaScript as a programming language -- especially now with jQuery and QUnit. It's more out of nostalgia for my earlier programming days doing DHTML applications than the fact that JavaScript is now chic in some circles.
This morning I found myself wanting some sort of method to check whether an Array object contained a value. I could have written the code inline, but it was cleaner to just add a new method to the Array class. Using the prototype object, I'll just add a method called "contains(value)" to all instances of Array:
Array.prototype.contains = function(value){
for (var i = 0; i < this.length; i++){
if (this
== value) return true;
}
return false;
}
In the middle of my code it's used like (actions is an array of all the available context menu actions for a row in a table):
function showMenuItem(actions, item){
if (actions.contains(item.id)){
$(item).show();
}
else{
$(item).hide();
}
}
I'm sure there's a better way to do what I did above, but dang that was easy. Yeah, C# has extension methods, but JavaScript had open classes first with fewer restrictions than the C# version.
Posted
09-08-2008 7:41 AM
by
Jeremy D. Miller