我正在尝试理解继承在JavaScript中是如何工作的。我很困惑“this”关键字是如何表现的。
我提供了我试图理解的显示类关系的实际代码。
class AAA {
xxx() {
return 2;
}
yyy() {
return 2;
}
zzz() {
return this.xxx() / 2;
}
}
class BBB extends AAA {
xxx() {
return super.xxx() * 2;
}
}
class CCC extends BBB {
yyy() {
return super.yyy() + this.xxx();
}
www() {
return this.xxx() - this.zzz();
}
}
class DDD extends AAA {
yyy() {
return super.yyy() + this.xxx();
}
www() {
return this.zzz() * this.yyy();
}
}
let c = new CCC();
console.log(c.www()); // 2
首先,我会解释一下我自己的理解。如果我错了,请纠正我。另外,如果你不介意,让我们同意'->‘的意思是为了简单起见。
1 c.www() -> CCC.www()
2 CCC.www() -> return this.xxx() - this.zzz()
3 this.xxx() -> BBB.xxx()
4 BBB.xxx() -> return super.xxx() * 2
5 super.xxx() -> AAA.xxx()
4
6 this.zzz() -> AAA.zzz()
7 AAA.zzz() -> return this.xxx() / 2
8 this.xxx() -> BBB.xxx()
9 BBB.xxx() -> return super.xxx() * 2
10 super.xxx() -> AAA.xxx()
2
// 4 - 2 = 2
如果我的解释是正确的。然后在第2行,this.xxx()
和this.zzz()
如何引用父类?此外,在第7行,this.xxx()
是如何引用类BBB的?
发布于 2019-06-10 00:21:07
所有的JavaScript对象都有一个原型。您可以将其视为到另一个对象的隐藏链接(或可见,取决于您的环境),以解析对未直接在对象本身上定义的任何属性(包括函数)的引用。
我发现类语法(实际上只是糖)暗示了基于类的继承,从而在幕后混淆了真正的机制。
虽然年事已高,但我仍然觉得这是最好的解释之一:
http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/
我也会阅读Eric Elliot写的任何关于继承的文章。
https://stackoverflow.com/questions/56515713
复制相似问题