简体   繁体   English

javascript - 自定义对象原型方法在数组循环中变为索引

[英]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 : 我为object定义了一个名为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??? 为什么getSize在那里?

edit I know that arrays in javascript are objects too. 编辑我知道javascript中的数组也是对象。 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: 因为getSize是一个可枚举的属性,所以您可以将其定义为不可枚举:

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. 因为["foo", "bar"]也是JavaScript中的对象。 Try to run typeof ["foo", "bar"] in console. 尝试在控制台中运行typeof ["foo", "bar"] It will return "object" to you. 它将向您返回"object" So you have extended Arrays methods too. 所以你也扩展了Arrays方法。 Once you have done this you will need to check for hasOwnProperty in all for..in iterations as well. 完成此操作后,您还需要在所有for..in迭代中检查hasOwnProperty

This happens to all global objects in JavaScript 这发生在JavaScript中的所有全局对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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