为什么Babel在已经使用Object.create(superClass.prototype)时使用setPrototypeOf进行继承? [英] Why does Babel use setPrototypeOf for inheritance when it already does Object.create(superClass.prototype)?

查看:259
本文介绍了为什么Babel在已经使用Object.create(superClass.prototype)时使用setPrototypeOf进行继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将以下代码发布到 Babel REPL

class Test {

}

class Test2 extends Test {

}

你得到这个继承 function

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;
}

直到我意识到它同时执行原型 a setPrototypeOf 调用中的Object.create 。我不熟悉 setPrototypeOf 所以我去了 MDN ,其中包含:

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:


如果你关心关于性能,你应该避免设置对象的[[Prototype]]。相反,使用Object.create()创建一个具有所需[[Prototype]]的新对象。

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?

该行应该是

if (superClass && !superClass.prototype)

原型未设置时,但它还有一个 __ proto __

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

推荐答案

setPrototypeOf 确实将 subClass 的[[prototype]]设置为原始值 Function.prototype superClass ,让它从中继承静态属性。

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 不能在这里使用(就像它用于 .prototype 对象),因为它不允许创建函数。显然,类的构造函数必须是一个函数;并且唯一的方法是使用标准表达式/声明创建函数,然后在之后更改其原型。

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.

这篇关于为什么Babel在已经使用Object.create(superClass.prototype)时使用setPrototypeOf进行继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆