I was trying to figure out a way to enumerate through properties of Math object when I realise that I can’t access any. Whaaat? Why?
Because they’re non-enumerable properties. By definition, when you define a non-enumerable property, you prevent the property from being accessed through for..in. The properties of built-in objects aren’t enumerable. Objects like window
and document
aren’t built-in, they’re defined by the browser and most likely enumerable by design.
Built-In Non-enumerable Objects
Global Object (ECMA) There is a unique global object (15.1), which is created before control enters any execution context. Initially the global object has the following properties: • Built-in objects such as Math, String, Date, parseInt, etc. These have attributes { DontEnum }.• Additional host defined properties. This may include a property whose value is the global object itself; for example, in the HTML document object model the window property of the global object is the global object itself. As control enters execution contexts, and as ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be changed.
Benefits of Creating Non-enumerable Properties
So what are the benefits of creating properties that can’t be accessed? Well, if you have the need to distinguish between properties that could and couldn’t be accessed, they could come in handy.
How do you create them? With Object.defineProperty(). E.g.
Object.defineProperty(obj, 'color', 'red');
And you could also tell if a specific property is enumerable with
obj.propertyIsEnumerable(property)
There you go! Keep ’em in mind when you find yourself puzzled with properties that can’t be accessed.
Reference:
http://stackoverflow.com/questions/2257993/how-to-display-all-methods-in-a-javascript-object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty