Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

JavaScript WTF #3: Foo.prototype is Not Prototype of Foo

0.00/5 (No votes)
3 Jan 2017Apache1 min read 5.1K  
Foo.prototype is not prototype of Foo

Consider the following code:

JavaScript
function Foo() {}
var fooPrototype = Object.getPrototypeOf(Foo);
console.log(Foo.prototype === fooPrototype); // false

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():

JavaScript
var obj = new Foo();
var objPrototype = Object.getPrototypeOf(obj);
console.log(Foo.prototype === objPrototype); // true

As for the actual prototype of Foo, it is Function.prototype:

JavaScript
console.log(fooPrototype === Function.prototype); // true

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?

  • 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.

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0