I want to create code(example) like this:
class foo {
static [x % 2 == 0]() {
return x / 2;
}
static [x % 2 == 1]() {
return x * 3 + 1;
}
}
I tried many ways but it didn’t work.
Is it possible to get the key value used to access a field in JavaScript?
Or is it possible to give default values to undefined fields?
class foo {
static a = 1;
static b = 2;
static default(x) = 6 + x;
}
> foo.a -> 1
> foo.b -> 2
> foo.c -> "6c"
> foo.d -> "6d"
... and so on
2
Answers
In JavaScript, the syntax you provided isn’t valid because you cannot directly define class fields or methods with dynamic names or conditional logic in the way you are attempting.
Consider using
Proxy
: