Consider:
function Foo() {}
var x = new Foo();
now x and Foo have the same prototype, but only Foo responds to .prototype:
Object.getPrototype(x) === Foo.prototype // true
x.prototype === Foo.prototype // false
Foo.prototype // Foo {} (depending on which browser)
x.prototype // undefined
Why doesn't x.prototype
work, but Foo.prototype
does work?
prototype
is a property of constructors that determines what the prototype of new objects created by that constructor will be. It's only useful to have such a property on a constructor.
As long as the prototype on the constructor hasn't been changed:
Object.getPrototypeOf( x ) === Foo.prototype
and that is the same as:
Object.getPrototypeOf( x ) === x.constructor.prototype
Note that generally:
Object.getPrototypeOf( Foo ) != Foo.prototype
Long story short: functions meant for new
have prototype
, object instances don't.
I'll probably fail in my precision in saying this, but the prototype
is something that only applies to what you might call constructor functions, which are functions meant to be called with new
to create instances. The prototype can be thought of as the template for the resulting instance.
For the resulting object, prototype
is not a property. Rather, the properties in the constructor's prototype are available as properties on the instance that was created. Meaning that when you look up a property on the instance, if it's not defined on the instance, Javascript will begin checking the prototype chain to see if it's defined there.
If you want to access the prototype of an instance, use Object.getPrototypeOf
.
The semantics of Javascript can be confusing. I highly recommend working through the free-to-read Javascript Allongé as a way to thoroughly understand some of Javascript's finer points. Chapter 8 focuses on exactly this topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With