繁体   English   中英

在 super() 中使用扩展 class 的 static 属性

[英]Use static property of extended class in super()

假设我们有代码

 class A { static foo = 1; constructor() { console.log(A.foo); } } class B extends A { static foo = 2; constructor() { super(); } } new A(); // prints "1" new B(); // also prints "1", but make it print "2"

这里A的构造函数正在访问A.foo A使用新的foo值扩展到B时,构造函数仍然打印1 ,即A.foo的值,而我真的希望它打印B.foo的值。

我将如何修改此代码,以便构造函数打印当前class 的foo属性?

使用constructor属性来访问 class 本身,然后您可以从中引用 static 属性。

 class A { static foo = 1; constructor() { console.log(this.constructor.foo); } } class B extends A { static foo = 2; constructor() { super(); } } new A(); // prints "1" new B(); // also prints "1", but make it print "2"

超级调用超级class的构造函数。

你可以做的是以下

 class A { static foo = 1; constructor(...args) { if(args.length == 1){ console.log(args[0].foo) } else{ console.log(A.foo); } } } class B extends A { static foo = 2; constructor(...args) { super(...args); // calls A.foo not B.foo } } new A(); // prints "1" new B(B); // pass the Class to it self as an arg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM