Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Babel use setPrototypeOf for inheritance when it already does Object.create(superClass.prototype)?

Posting the following code into the Babel REPL

class Test {

}

class Test2 extends Test {

}

you get this inherits function

function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

It looked fine to me until I realized it was doing both Object.create on the prototype and a setPrototypeOf call. I wasn't that familiar with setPrototypeOf so I went to the MDN where it says:

If you care about performance you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().

Which is confusing to me since they use both. Why is this the case?

Should the line instead be

if (superClass && !superClass.prototype)

for when the prototype is unset, but it still has a __proto__?

like image 838
m0meni Avatar asked Jun 20 '16 15:06

m0meni


1 Answers

The setPrototypeOf does set the [[prototype]] of subClass from its original value Function.prototype to superClass, to let it inherit static properties from it.

Object.create cannot be used here (like it is for the .prototype object), as it does not allow to create functions. The constructor of a class has to be a function though, obviously; and the only way to do that is to create functions using standard expressions/declarations and then change its prototype afterwards.

like image 127
Bergi Avatar answered Oct 31 '22 04:10

Bergi