Javascript prototype through Object.create()

javascript, prototype

Solution

The important thing here is that the `prototype` property 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 via `new someObj`. Prior to ES5, you can't directly access the prototype of an object; as of ES5, you can, via `Object.getPrototypeOf`.

Re

`alert(p.prototype); // UNDEFINED, but why?`

The reason is that the `p` object 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 `prototype` so 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:

function Foo() {
}
Foo.prototype.answer = 42;

console.log(Foo.prototype.answer); // "42"
var f = new Foo();
console.log(f.answer); // "42"

That last line works like this:

- Get the `f` object.

- Does `f` have its own property called "answer"?

- No, does `f` have a prototype?

- Yes, does the prototype have its own property called "answer"?

- Yes, return the value of that property.

You've mentioned `Object.create` in the title of your question. It's important to understand that `Object.create` is 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.

Problem

``` 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?

Original source