我注意到使用 Babel,如果我转译
class Rectangle {
a = 1;
}
使用 stage-0,则生成的代码具有构造函数,但不调用super()
但如果代码更改为:
class Rectangle extends Object {
a = 1;
}
那么转译的代码是:
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
class Rectangle extends Object {
constructor(...args) {
super(...args);
_defineProperty(this, "a", 1);
}
}
原始代码的版本 1 和版本 2 实际上不是相同的吗?(所有类都扩展了对象(。所以如果版本 1 不调用super()
,看起来 Object 的构造函数什么都不做,所以版本 2 也没有理由调用它?
原始代码的版本 1 和 2 实际上不是相同的吗?(所有类都扩展了对象(。
不,不完全是。让我们比较一下:
class Base {
}
和
class Sub extends Object {
}
的确,Base.prototype
和Sub.prototype
都使用Object.prototype
作为原型,但这并不能使它们相同。两个区别:
Base
(构造函数(使用Object
作为其原型;Sub
使用Function.prototype
.- 当您通过
new
调用对象时,Base
将创建对象;Sub
不会,它期望超类构造函数(Object
(这样做。这意味着它必须调用它。(构造函数被标记以指示它们是基类构造函数还是子类构造函数,并且new
运算符的处理会根据此进行。
演示 #1(使用 ES2015+ JavaScript 引擎(:
class Base {
}
class Sub extends Object {
}
// Both `prototype` properties inherit from `Object.prototype`
console.log(Object.getPrototypeOf(Base.prototype) === Object.prototype);
console.log(Object.getPrototypeOf(Sub.prototype) === Object.prototype);
// But the constructors themselves inherit from different things
console.log(Object.getPrototypeOf(Base) === Function.prototype);
console.log(Object.getPrototypeOf(Sub) === Object);
所以如果版本 1 不调用
super()
,看起来Object
的构造函数什么都不做,所以版本 2 也没有理由调用它?
它必须称之为。这无法在原生JavaScript(ES2015+(中编译:
class Example extends Object {
constructor() {
this.foo = "bar";
}
}
console.log(new Example().foo);
如果您有extends
,则必须调用super
才能创建新对象。
我在答案顶部的Sub
编译,因为它没有显式构造函数,因此它获得了默认的子类构造函数(constructor(...args) { super(...args); }
(。但是Example
失败了,因为它有一个显式构造函数,但没有进行super
调用。