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