So I have the empty object a = {}. When I do console.log(a), console.dir(a), or even
for(b in a) {
console.log(b);
}
I do not get to see the “hidden properties” such as __defineGetter__, hasOwnProperty, etc.
How can I print all properties of an object?
What you’re after is the non-enumerable properties of an object (and possibly those it inherits from its prototype). I don’t believe there’s any standard way to get them via JavaScript.
If you use a debugger and inspect an object, usually all properties of an object are shown (not just the enumerable ones). All major browsers have built-in debuggers now: Chrome has Dev Tools (Ctrl+Shift+I); IE8 and up have “F12 Developer Tools”; IE7 and earlier can be debugged via the free version of VS.Net; recent versions of Firefox have tools built in, for older versions you can get the Firebug plug-in; Opera has Dragonfly.
Update: In the comments on the question you’ve said:
Right.
{}has no properties at all, just a prototype. If you click the little arrow to the left of__proto__, it will show you__proto__‘s properties.hasOwnProperty,toString, etc., are all properties{}gets from the prototype (which isObject.prototype), not properties of the object itself.JavaScript uses prototypical inheritance, which means an object is backed by a prototype. If you try to retrieve the value of a property the object doesn’t have, the JavaScript engine will look at the object’s prototype to see if the prototype has that property; if so, that value is used. If the prototype doesn’t have it, the engine looks at the prototype’s prototype; and so on until it reaches the root of the hierarchy. This is why you hear about objects having their own properties vs. properties they inherit.
Here’s an example:
Here’s a constructor function. We put a property on the prototype the JavaScript engine will assign if we use
new Footo create an object.Let’s create an object using that constructor:
fhas no properties at all, and yet:…because since
fdoesn’t have a property called “bar”, the engine looks onf‘s prototype, which is theFoo.prototypeobject.Now let’s give
fits own “bar” property:Now let’s remove
f‘s “bar” property:What will happen if we try to retrieve
f.barnow?If you said
42, you get top marks. Becausefno longer has a property called “bar”, we go back to getting it from the prototype.Note that this relationship is live, so:
In the 3rd edition of ECMAScript (most browsers implement something along the lines of the 3rd edition), the only way to assign a prototype to an object is via a constructor function’s
prototypeproperty, as above. With the 5th edition, a more direct way was added:Object.create, which you can pass a prototype object to directly: