Inherited non-enumerable properties in for…in loop

2019-07-20 17:49发布

问题:

I have an object p, with an enumerable propery x.

var p = Object.create(Object.prototype, {
  x: {
    value: "frog",
    enumerable: true
  }
});

I create an object, that inherits from p, and overrides property x, with a non-enumerable property

var o = Object.create(p, {
  x: {
    value: "bird",
    enumerable: false
  }
});

What do you think, will the property x be enumerated in a for...in loop of o?

for (var n in o) {
  console.log(n);
}

Well, in Chrome and IE9 it will be enumerated (which is, I think, quite wierd); in FF, it won't be enumerated.

Which one is the right behaviour?

Here is a complete example: http://jsfiddle.net/hnvsM/3/

回答1:

This is a known bug in V8. There's been a bug report on this for quite a while.

Issue 705: Non-enumerable property fails to shadow inherited enumerable property from for-in



回答2:

According to this, it's definitely a bug in chrome and ie9. Emphasis mine.

Enumerating the properties of an object includes enumerating properties of its prototype, and the prototype of the prototype, and so on, recursively; but a property of a prototype is not enumerated if it is “shadowed” because some previous object in the prototype chain has a property with the same name. The values of [[Enumerable]] attributes are not considered when determining if a property of a prototype object is shadowed by a previous object on the prototype chain.