[英]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.