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__
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…