javascript - Babel 已经做了 Object.create(superClass.prototype) 为什么还要用 setPrototypeOf 来继承?

标签 javascript inheritance ecmascript-6 babeljs

将以下代码发布到 Babel REPL

class Test {

}

class Test2 extends Test {

}

你得到了这个inherits函数

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

在我意识到它在原型(prototype)上执行Object.createsetPrototypeOf 调用之前,它看起来不错。我不太熟悉 setPrototypeOf 所以我去了 MDN它说:

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().

这让我感到困惑,因为他们同时使用了这两者。为什么会这样?

这条线应该是

if (superClass && !superClass.prototype)

当原型(prototype)未设置,但它仍然有一个 __proto__ 时?

最佳答案

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

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

关于javascript - Babel 已经做了 Object.create(superClass.prototype) 为什么还要用 setPrototypeOf 来继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37926910/

相关文章:

python - 通过调用父类(super class)python创建子类

c# - 我可以让我的类在运行时从另一个类继承吗?

javascript - 如何匹配值,然后为对象添加值?

javascript - 如何在我的 Protractor 测试中设置 3 个日期?

javascript - 将具有 , 的字符串替换为 $

javascript - 如何将 SVG 导出为 PNG 格式

javascript - ES6 模块导入是否执行导入文件中的代码?

javascript - TinyMCE:如何让用户在 "readonly: true;"时标记文本

java - Object类怎么可能是子类的父类(super class)呢?

javascript - 如何从对象数组的多个键中获取所有值?