Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

javascript - 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__?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...