var someObj = function() { }
var p = new someObj();
alert(someObj.prototype); // This works
alert(p.prototype); // UNDEFINED, but why?
someObj.prototype.model= "Nissan";
alert(p.model); // This works! I understand the dynamic nature of prototypes, but doesn't that mean that p.prototype === someObj.prototype?
Why is this so? Since “p” is an instance of “someObj”, why is the prototype undefined? I mean, when I add a property to “someObj” prototype, it is accessible to “p”, so why is the prototype not accessible?
The important thing here is that the
prototypeproperty of function objects is not the prototype of an object. It’s the object that will be assigned as the prototype of an object you create vianew someObj. Prior to ES5, you can’t directly access the prototype of an object; as of ES5, you can, viaObject.getPrototypeOf.Re
The reason is that the
pobject doesn’t have a property called “prototype”. It has an underlying prototype, but that’s not how you access it.All function objects have a property called
prototypeso that if they’re used as constructor functions, we can define what the properties of the underlying prototype of the objects created by those constructors will be. This may help:That last line works like this:
fobject.fhave its own property called “answer”?fhave a prototype?You’ve mentioned
Object.createin the title of your question. It’s important to understand thatObject.createis quite separate from constructor functions. It was added to the language so that if you preferred not to use constructor functions, you didn’t have to, but could still set the prototype of an object — directly, when you create that object.