Non-enumerable properties appear in for…in loop in Chrome

前端 未结 2 543
挽巷
挽巷 2021-01-02 00:40

A for-in loop will go through all enumerable properties of an object, even those in the prototype chain. The function hasOwnProperty c

相关标签:
2条回答
  • 2021-01-02 00:58

    Chrome is weird:

    for(a in window)
        if(window.hasOwnProperty(a) && window.propertyIsEnumerable(a))
            console.log(a);
    

    It puts out about 30 properties compared to like 450 the other way, in chrome.

    0 讨论(0)
  • 2021-01-02 01:13

    The sad fact is that JavaScript engines are not the same. While ES5 conforming engines will dutifully respect the enumerability of their properties, window is a host object, as pointed out by pimvdb and Felix above, and not beholden to the rules of ES5.

    You can see more evidence of what window object actually is in window.constructor, which will show it as being constructed from

    function Window() { [native code] }
    

    As such, we have no real way of determining why certain properties are enumerable (according to Chrome), and others are not from within the JavaScript runtime.

    However, you can still see the full state of Chrome's inconsistent window enumerable properties by looking at Object.keys(window) which according to its MDN article, "returns an array of all own enumerable properties found upon a given object."

    Doing so still returns an array of 30-odd properties. Chalk it up to Chrome strangeness!

    EDIT: With some further testing, I found the proper way for Chrome to make sense as to window's enumerable properties

    Object.keys(window).filter(function(prop) {
      return window.hasOwnProperty(prop) && !window.propertyIsEnumerable(prop);
    });
    

    It would seem that in Chrome, the candidate list of properties for enumeration by for...in is NOT what is returned by Object.keys, but actually much closer to Object.getOwnPropertyNames which lists enumerable and non-enumerable properties. However, even that is inconsistent. The list of properties that are window.hasOwnProperty(prop) && !window.propertyIsEnumerable(prop) come out to 423 and 454 for for...in and Object.getOwnPropertyNames, respectively, in my testing.

    0 讨论(0)
提交回复
热议问题