我试图理解手册中的一行:
在 ES2015 中,隐式返回对象的构造函数将
的值替换为this
的任何调用者。生成的构造函数代码有必要捕获super(...)
的任何潜在返回值并将其替换为super(...)
。this
整条线对我来说都很模糊。有人可以解释一下这里发生了什么吗?
super
“函数调用”很奇怪。对于不返回对象的普通类,this
只是正在构造的类的当前实例。对 super()
的调用只是对同一个 this
进行操作,因此最终构造的对象是子类的实例:
class Foo {
a = 10;
constructor() { }
}
class Bar extends Foo {
z: number;
constructor() {
super();
this.z = 1;
}
}
const b = new Bar();
console.log(b); // Bar: {a: 10, z: 1}
console.log(b instanceof Bar); // true
但是,如果超类从其构造函数返回一个值,那么子类中的
this
就会变成该值。这允许对 this
的后续引用可以引用超类返回的同一对象。因此,子类的行为“正常”,只是构造的对象实际上不是该类的实例:
class Foo {
constructor() {
return { a: 10 };
}
}
class Bar extends Foo {
z: number;
constructor() {
super();
this.z = 1;
}
}
const b = new Bar();
console.log(b); // {a: 10, z: 1}
console.log(b instanceof Bar); // false
这意味着对
super()
的调用必须看起来像“像函数一样调用超类构造函数,并查看它是否返回任何内容”。如果是这样,则将该函数的结果分配给this
。好像你会写一样
this = superCtor.call(this) || this;
但你不能这么做!您无法分配给
this
。但它无论如何都会发生,隐含地。如果你看看当downleveling代码到class
存在之前的JS版本时调用超级构造函数时会发生什么,你会看到类似的东西:
function Bar() {
var _this = _super.call(this) || this;
_this.z = 1;
return _this;
}
您会看到实际的
this
已随处替换为新的 _this
变量。