3

The title says its all, but here's the code:

class A {}
class B extends A {}

const b = new B()


Object.getPrototypeOf(b.constructor) === b.constructor.prototype // false

Object.getPrototypeOf(b.constructor) === A // true
b.constructor.prototype === A // false. why?

I mean, the code above is counter-intuitive. Why is it made this way?

Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89

2 Answers2

2

__proto__ and prototype is not the same.

Let's say you have an object obj. Now, obj.prototype won't actually provide you with the prototype of obj, as you expect. To get the prototype of obj you have to do obj.__proto__. Run the following code and you'll have your answer. Also, Read this to know more about the differences between __proto__ and prototype. :)

class A {}
class B extends A {}

const b = new B()

console.log(Object.getPrototypeOf(b.constructor) === b.constructor.__proto__) // true
console.log(Object.getPrototypeOf(b.constructor) === A) // true
console.log(b.constructor.__proto__ === A) // true
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
1

In your code:

b.constructor.prototype === A; // false

This is false because the prototype of b is the prototype of A not A itself. This may sound confusing at first so I left an example below:

class A {}
class B extends A {}

const b = new B()


Object.getPrototypeOf(b.constructor) === b.constructor.prototype // false

Object.getPrototypeOf(b.constructor) === A // true
b.constructor.prototype === A // false. why?

console.dir(b.constructor.__proto__ === A); // true

In this example in the last statement:

console.dir(b.constructor.__proto__ === A); // true

The __proto__ property of b actually refers to the same object, A.

You may find the following also interesting:

class A {}

console.log(typeof A); // constructors are merely masked functions with added functionality

console.log(typeof A.__proto__);  // constructors inherit from the Function object

console.log(typeof A.__proto__.__proto__); // the Function object inherits from Object object
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155