我注意到了 using 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 实际上不是一样的吗? (所有类都扩展了 Object)。因此,如果版本 1 不调用 super()
,看起来 Object 的构造函数什么也没做,那么版本 2 也没有理由调用它吗?
最佳答案
Isn't version 1 and 2 of the original code actually the same? (all classes extend Object).
不,不完全。让我们比较一下:
class Base {
}
和
class Sub extends Object {
}
确实 Base.prototype
和 Sub.prototype
都使用 Object.prototype
作为它们的原型(prototype),但这并不能使它们成为原型(prototype)相同。两个区别:
Base
(构造函数)使用Object
作为它的原型(prototype);Sub
使用Function.prototype
。Base
将在您通过new
调用它时创建对象;Sub
不会,它希望父类(super class)构造函数 (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);
And so if version 1 doesn't call
super()
, it looks like the constructor ofObject
doesn't do anything, so version 2 also has no reason to call it?
它必须调用它。这无法在原生 JavaScript (ES2015+) 中编译:
class Example extends Object {
constructor() {
this.foo = "bar";
}
}
console.log(new Example().foo);
如果你有一个extends
,你必须调用super
来创建新对象。
My Sub
编译是因为它没有显式构造函数,所以它获得默认的子类构造函数 (constructor(...args) { super(. ..args); }
).但是 Example
失败了,因为它有一个显式构造函数但没有进行 super
调用。
关于javascript - 如果一个类扩展了 Object,Babel 真的不需要调用 super() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60007028/