簡體   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