简体   繁体   中英

javascript - custom object prototype method turns into index in array loop

Here's something weird. I have defined a custom prototype method for object called getSize :

if (!Object.prototype.getSize) {
    Object.prototype.getSize = function() {
        var size = 0, key;
        for (key in this) {
            if (this.hasOwnProperty(key)) size++;
        }
        return size;
    };
}

It gives you the size of an object. Pretty simple so far, right? Here's where I get confused:

var l = ["foo", "bar"]
for (var i in l) {
    console.log(i);
}

results are:

0
1
getSize

Why is getSize there???

edit I know that arrays in javascript are objects too. My question is why is the method turned into an index, instead of remaining a method. It doesn't make any sense to me...

Because getSize is an enumerable property, you could define it to be non-enumerable:

Object.defineProperty(Object.prototype, 'getSize', {
  enumerable: false,
  value: function() {
    var size = 0, key;
    for (key in this) {
      if (this.hasOwnProperty(key)) size++;
    }
    return size;
  }
});

But you could also do:

Object.keys(object).length;

Because ["foo", "bar"] is an Object in JavaScript too. Try to run typeof ["foo", "bar"] in console. It will return "object" to you. So you have extended Arrays methods too. Once you have done this you will need to check for hasOwnProperty in all for..in iterations as well.

This happens to all global objects in JavaScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM