NB: This post is not about the Prototype framework.

AJAX has caused something of a renaissance for JavaScript over the past couple of years, so I’m still learning (and relearning) a lot of things about it despite having started using it seven years ago. One thing I revisited today was adding a method to an existing JavaScript object as an elegant alternative to defining a procedural-style function.

JavaScript is object-oriented, which makes it elegant and powerful when manipulating the DOM, because objects in an OO language belong to one another just like elements of an HTML page belong to one another, i.e. in a hierarchical model.

JavaScript’s OO capabilities are, however, limited compared to other languages. You can’t take one object and use it as a basis for new one using extends.

You can, however, add your own home-made methods and properties to existing objects, including pre-made ones (such as String and Array). For example, you could add a function to the Array object to help you find out if an array contains a certain value.

Array.prototype.contains = function(value) {
 for (var i=0; i<this.length; i++) {
  if (this[i] == value) {
   return true;
  }
 }
 return false;
}

Now, any Array which you create has the contains function. It’s more elegant than writing a procedural function, e.g. contains(array, value), which is what I’ve become used to as a result of using the many useful inbuilt procedural functions in PHP.