Search code examples
javascriptdefinitionfunction-prototypes

JS function given to Array.prototype seen as array property


Array.prototype.testi = function() {console.log('hep');}
var b = new Array();

b.push(1, 5, 'b', 'c');

for (var i in b) {
    console.log(b[i]);
}

This will log (in chrome)

1
2
b
c
function () {console.log('hep');}

Or live example in http://jsfiddle.net/marqs/6VVka/1/

My question is, why is the function shown in the listing, even though it's given to the array prototype?

This has implications for extending browser functionalities that aren't used (for ex. IE extended Array.filter will behave differently if array in is used etc).

Edit: to clarify, I have no access to the code that does the for-in loop, as it's an external library. Thus the formulation of the question, more about "why is this so" than how to fix this.


Solution

  • JavaScript Objects are a collection of properties. Inside these properties, there are properties that describe the properties. The main one you are looking at here is the [[Enumerable]] property, which is a meta-property extended to most of the default objects in JavaScript, such as Array and Object. ECMAScript 5 defines a method for adding non-[[Enumerable]] objects, but that may not be widely supported in browsers.

    One way to prevent enumerating over object properties you don't want is to check if the object property has an internal property method called [[GetOwnProperty]]. This ensures the property was directly invoked on the object and NOT inherited somewhere along the prototype chain.

    var arr = ['a','b','c'], indexes = [];
    Array.prototype.each = function() {/*blah*/}; 
    
    for (var index in arr) {
        if (arr.hasOwnProperty(index)) {
        indexes.push(index);
        }
    }
    
    indexes; //["0", "1", "2"]
    

    Source: http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/