Possible Duplicate:
Adding functions to javascript's Array class breaks for loops
Before anyone says anything, I know it's generally bad practice to assign something with Object.prototype, but this is something that I want ALL objects to have if this chunk of code is included. It's also odd that it's happening when I do it with Array as well. This is taking place in Node.js, so it's with the V8 javascript engine. Anyways, here's what's going on. I'm just assigning a function to the prototype of one of these two types (I've tried both individually with the same error as the outcome, and it doesn't happen when I use other types).
Array.prototype.test = function() { console.log("test"); }
var a = ["test1", "test2", "test3"],
index,
entry;
a.test(); //prints 'test'
for(index in a) {
entry = (a[index]).split("e"); //throws an error
}
The error is
Object Function () {console.log("test");} has no method 'split'
thoughts?
If you run this, you will see what's going on because you used prototype on array, the function becomes part of the object, and split on that throws the error.
Array.prototype.test = function() { console.log("test"); }
var a = ["test1", "test2", "test3"],
index,
entry;
a.test(); //prints 'test'
for(index in a) {
console.log(index);
console.log(a);
// entry = (a[index]).split("e"); //throws an error
}
you should iterate that array with:
for(index=0;index<a.length;index++)
because when you add members they become part of the array, see it better with
for(i in a) console.log(i);
this will print all the keys plus the function name "test"
Try
varTest = console.log("test");
Array.prototype.test = function() { varTest }
var a = ["test1", "test2", "test3"],
index,
entry;
a.test(); //prints 'test'
for(index in a) {
entry = (a[index]).split("e"); //throws an error
}