我有这种情况
import assert from 'assert'
class A {
static x = 0
static a () {
return A.x
}
}
class B extends A {
static x = 1
}
assert.equal(B.a(), 1)
我需要从 Js es6 中的基类检索派生类中的静态值。 但是,我找不到办法,
断言将失败
AssertionError [ERR_ASSERTION]: 0 == 1
正确的做法是什么?
- 谢谢
最佳答案
在这里,您直接请求 A.x
。你应该调用 this.x
来获取 A.x
当你在一个类型为 A
的对象上并获取 B.x
当您在类型为 B
的对象上时。
只需进行以下更改,它应该可以正常工作:
static a () {
return this.x;
}
关于Javascript 访问静态子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47480452/