【发布时间】:2020-10-21 16:13:36
【问题描述】:
这与an old question 有关,但我特意询问如何使用旧的编写函数的方式扩展一个新的 ES6 类。
以下代码不起作用。
class X {
a;
constructor(a) {
this.a = a;
}
}
X.call({}, 3); // Uncaught TypeError: Class constructor X cannot be invoked without 'new'
有没有办法间接调用构造函数?例如,我是否可以使用老式的原型继承来制作 Y?
function Y(a) {
X.call(this, a); // this doesn't work here, can't use super as well
}
Y.prototype = Object.create(X.prototype);
Object.setPrototypeOf(Y, X);
const y = new Y(12);
【问题讨论】:
-
我很好奇,当您扩展使用
class创建的构造函数并且您使用的是ES2015+ 时,为什么要使用传统函数而不是class?