Click here to Skip to main content
15,885,771 members
Articles / Programming Languages / Javascript

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

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
3 Jan 2017Apache1 min read 5K  
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.
This article was originally posted at http://www.ikriv.com/blog?p=2235

License

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


Written By
Technical Lead Thomson Reuters
United States United States
Ivan is a hands-on software architect/technical lead working for Thomson Reuters in the New York City area. At present I am mostly building complex multi-threaded WPF application for the financial sector, but I am also interested in cloud computing, web development, mobile development, etc.

Please visit my web site: www.ikriv.com.

Comments and Discussions

 
-- There are no messages in this forum --