Search code examples
javascriptobjectfor-in-loopprototype-oriented

Javascript extend prototype, and for-in


I've tried to add some new functions to the Array prototype, that I use frequently. My question is how when I add something to the prototype of an Object, and trace out properties in a for-in loop of any new array (object) that I created, those new functions that were added only to the prototype are listed as well? Shouldn't they just be in proto?

Just for example: So I add an function of "first" to the prototype.

Array.prototype.first = function() { return this[0]; }

So when now I use an for-in loop to iterate over the array, I get the named function, as well as any other items that are in the array.

var array = [1,2,3];   

//traces out: 1,3,4,first
for(var i in array) {
   console.log(i);
}

Is this something that is solely resulting from the trace and/or use of for-in for iterating over an object?


Solution

  • Evan is correct. However, when using for..in statements in javascript, it is always best to test that the current attribute is a property of the object and not something inherited from the prototype chain:

    for(var attr in obj){
       if(obj.hasOwnProperty(attr)){
           // first will not appear here
       }
    }