2

I am trying to understand how classes are working behind the scenes in ES6 and one thing that is rather unclear is how the prototypes are set for the child class. Here is the article I am reading:

https://medium.com/@robertgrosse/how-es6-classes-really-work-and-how-to-build-your-own-fd6085eb326a

There we see the following two lines:

Object.setPrototypeOf(Child, Base);
Object.setPrototypeOf(Child.prototype, Base.prototype);

When we create a Child class, since Child is a constructor function behind the scenes, I would expect Child.prototype to be used for its creation, so the second line in the inheritance explanation is clear for me:

Object.setPrototypeOf(Child.prototype, Base.prototype);

However, whats the purpose of the first line - Object.setPrototypeOf(Child, Base); - and how it is useful? (I might not clearly understand the second line either though fully too)

Nikita Vlasenko
  • 4,004
  • 7
  • 47
  • 87
  • 2
    Near-duplicate of [Why does Babel use `__proto__` for inheritance](https://stackoverflow.com/questions/28674356/6to5-compiler-use-proto-for-inheritance) (but there's no way you could've found that :D) – Bergi Aug 26 '20 at 23:34
  • It is not really because it deals with other code not related to the cited question, it relates to the way classes are working beneath the surface, even though the underlying mechanism is the same. – Nikita Vlasenko Aug 28 '20 at 15:47

1 Answers1

2

Child constructors inherit from the base constructors so that things like static functions behave sensibly, for example:

class Base {
  static function foo() { return 42; }
}
class Child extends Base {}

console.log(Child.foo() === 42); // true

Base.prototype and Child.prototype do not come into play here at all because there are no instances of the class, so the constructors themselves also use inheritance. When implementing this without class syntax, you then end with

function Base() {}
Base.foo = function foo() { return 42; };

function Child() {}
Object.setPrototypeOf(Child, Base);
Object.setPrototypeOf(Child.prototype, Base.prototype);

console.log(Child.foo() === 42); // true
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251