Why is JavaScript prototype property undefined on new objects?
Only constructor functions have prototypes. Since x
is a constructor function, x
has a prototype.
b
is not a constructor function. Hence, it does not have a prototype.
If you want to get a reference to the function that constructed b
(in this case, x
), you can use
b.constructor
The .prototype
property of a function is just there to set up inheritance on the new object when the function is invoked as a constructor.
When the new object is created, it gets its internal [[Prototype]]
property set to the object that the function's .prototype
property points to.
The object itself doesn't get a .prototype
property. Its relationship to the object is completely internal.
That's why it works to do b.log()
. When the JS engine sees that the b
object itself has no log
property, it tries to look it up on the objects internal [[Prototype]]
object, where it successfully finds it.
To be clear, the [[Prototype]]
property is not directly accessible. It's an internal property that is only indirectly mutable via other constructs provided by the JS engine.