Consider the following code:
function Foo() {}
var fooPrototype = Object.getPrototypeOf(Foo);
console.log(Foo.prototype === fooPrototype);
Why is it false? Because Foo.prototype
is in fact not the prototype of Foo
, but the prototype of objects created via expression new Foo()
:
var obj = new Foo();
var objPrototype = Object.getPrototypeOf(obj);
console.log(Foo.prototype === objPrototype);
As for the actual prototype of Foo
, it is Function.prototype
:
console.log(fooPrototype === Function.prototype);
This is very confusing for someone who is trying to learn about prototypes. Although JavaScript is built on prototypes, it is inexplicably shy about discovering and working with prototypes. To the best of my knowledge, Object.getPrototypeOf()
was added only in EcmaScript 5.1, 14 years after JavaScript’s inception. For older versions of JavaScript, it is recommended to use obj.constructor.prototype
to retrieve prototype of obj
. This is rather indirect, and it would fail if someone reassigns the constructor
property.
To visualize how ridiculous this situation is, let’s mentally transfer it to another language. The concept of prototypes is as central to JavaScript as the concept of base (super) classes to object-oriented languages. A similar situation in Java would mean that:
This would make Java language a little bit of a mess, and we would ask WTF, wouldn’t we?
CodeProject
- There is no keyword
super
. - You can refer to the superclass portion of your object as
this.constructor.super
. - There is a non-standard property
__super__
supported only on some JVMs, but not others. - Method
Object.getSuperOf()
is finally added in Java 7. - For any class C, expression
C.super
yields Class.class
.