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__?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With