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 ...
 
Firstly I would like to thank you for your site Dave as it has helped me out of a couple of tight spots. I think I have a solution to your problem which allows you to use prototypes without returning the prototyped object in your arrays and or objects - works for both!

function objectForInLoop(myObject){
myArray = [];
for(objectName in myObject){
if(myObject.hasOwnProperty(objectName)) {//This line is the key it will ignore protypes
var currentObj = myObject[objectName]
myArray.push(objectName);
}
}
return myArray;
}
 
Dan: The problem here is that if you add a method to an object, you potentially break other people's code. Indeed, in your own scripts, you can work around the issue, but if you're cooperating with other people who don't know to use the work-around, their code can be broken by this.

That's what happened to me (seems a long time ago now) so I swore off doing this.
 
Post a Comment

<< Home

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