Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Stephen O'Connor
22,291 PointsWhy is an empty object literal's constructor and prototype different to one that has properties?
Hello.
I am trying to learn JavaScript in depth and I don't understand why an empty object literal has a different constructor and prototype than one that has properties. Can someone explain or point me in the direction of somewhere that might tell me?
To explain what I mean (from the Chrome developer tools):
var name = {};
var age = {age: 33};
console.log(name.constructor);
String() { [native code] }
console.log(age.constructor);
Object() { [native code] }
console.log(name.__proto__);
String {length: 0, [[PrimitiveValue]]: ""}
console.log(age.__proto__);
Object {}__defineGetter__: __defineGetter__()__defineSetter__: __defineSetter__()__lookupGetter__: __lookupGetter__()__lookupSetter__: __lookupSetter__()constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get __proto__: get __proto__()set __proto__: set __proto__()
I thought the constructor and prototype of all object literals was Object, but an empty one has String.
2 Answers
akak
29,446 PointsHi,
You are getting String in the first one because there is a property called "name" on the Function object. And by trying to get a constructor for name - you are accessing this property constructor which is String. (as it's just a string) Look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
If you'd do:
var foo = {}
console.log(foo.constructor);
you'll get: function Object() { [native code] } as expected.
Also because of that the prototype is different. Prototype of empty object assigned to foo will be the same as your age object.
You just had a bad luck to stumble upon internal JS stuff. name is on that list: http://www.w3schools.com/js/js_reserved.asp
Stephen O'Connor
22,291 PointsAh, thanks Akak. I was ripping my hair out yesterday trying to figure it out. Thanks for clearing that up. Back to the books!!