3

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...

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

4 Comments

I didn't know methods have an enumerable definition. This is very cool, thanks for the answer! I'll use defineProperty from now on
btw, Object.keys(l) returns ['0', '1'] even if I don't set enumerable: false - how come?
@yuvi because Object.keys doesn't use the prototype chain. All of this stuff is well documented on MDN.
@DaggNabbit thanks. MDN is well documented, but that doesn't mean you always know where to look or what this and that means. Obviously, Object.keys doesn't go through the same process as for...in, because then you would get the same results. I'm wondering what that process is though (or does that happen on a very low level of code?)
3

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

2 Comments

I know that arrays are objects too. But why doesn't it inherit the method, why is it turned into an index? That makes no sense
elclanrs answer to this. You can read more about enumerables at MDN developer.mozilla.org/en-US/docs/Web/JavaScript/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.