Javascript 既然巴贝尔已经创建了Object.create(superClass.prototype),为什么还要使用setPrototypeOf进行继承呢?
将以下代码发布到 您将获得此Javascript 既然巴贝尔已经创建了Object.create(superClass.prototype),为什么还要使用setPrototypeOf进行继承呢?,javascript,inheritance,ecmascript-6,babeljs,Javascript,Inheritance,Ecmascript 6,Babeljs,将以下代码发布到 您将获得此继承函数 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); } subC
继承
函数
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;
}
在我看来它很好,直到我意识到它同时在原型上创建Object.create
和setPrototypeOf
调用。我对setPrototypeOf
不太熟悉,所以我去了一个网站,上面写着:
如果您关心性能,则应避免设置对象的[[Prototype]]。相反,使用object.create()创建具有所需[[Prototype]]的新对象
这让我很困惑,因为他们两个都用。为什么会这样
这条线应该改为
if (superClass && !superClass.prototype)
因为当原型未设置时,它仍然有一个
\uu proto\uuu
?setPrototypeOf
确实将子类的[[prototype]]从其原始值函数设置为超类,让它从中继承静态属性
此处不能使用对象.create
(与.prototype
对象类似),因为它不允许创建函数。显然,类的构造函数必须是函数;唯一的方法是使用标准表达式/声明创建函数,然后再更改其原型。Hmmm这让我有点困惑。您能否创建一个Object.create()
缺点的代码示例?从我阅读的内容来看,它将继承静态方法,因为这些只是在原始类的原型上定义的方法,对吗?@AR7:静态方法是在类的构造函数函数对象上定义的,而不是在.prototype
对象上定义的。这里我们讨论的是相互继承的构造函数,而不是实例的原型链。您可以执行Object.create(superClass)
,但这会创建一个对象(正如方法名称所说),而不是子类
函数。静态方法不存储在任何\uuuuu proto\uuuu
上,它们存储在构造函数本身上。它们不存储在.prototype
上,因为它们不应该由实例继承。从中继承属性的[[prototype]]与构造函数的.prototype
属性不同@AR7本质上,您只能通过引用“类”本身而不是通过该类的任何实例来访问它们。这就是为什么你不希望它们出现在原型上。
if (superClass && !superClass.prototype)