Saturday, August 25, 2007

 

Methods hit wall

I've gone off attaching methods to core JavaScript classes. This week, I've had two scripts fail dismally because of it, so even though the format of working with:
Object.prototype.isInArray = function(myArray){
  for (var i=0; myArray.length > i; i++) {
    if(myArray[i] == this){
      return true;
    }
  }
  return false;
}
is so convenient
if (myObj.isInArray(myArray)) {
or with:
Array.prototype.contains = function(myString){
  for (var i=0; this.length > i; i++) {
    if(myString == this[i]){
      return true;
    }
  }
  return false;
}

if (myArray.contains(myObj)) {
They can really backfire and slap you in the face if you're doing work that involves creating objects or arrays and examining their contents. So, I'm back to the prosaic but safe:
function arrayContains(anArray, anItem) {
  for (var i = 0; anArray.length > i; i++) {
    if (anItem == anArray[i]) return true;
  }
  return false;
}

if (arrayContains(myArray, myObj)) {
Which most people would have been using all along anyway.

Comments:
There are indeed several cases where additonal member functions can blow into your face - you should have mentioned a few.
This is only about the very basic classes, such as Object and Array. You can still benefit from member functions if you keep them confined to their own classes. They can also be helpful in the InDesign collection classes.

function MyArray() {}
MyArray.prototype.contains = function ...
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?