javascriptclassstatic

JavaScript Defining static fields with conditions in a class


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

Solution

  • Consider using Proxy:

    class Foo {
      static a = 1;
      static b = 2;
    }
    
    const foo = new Proxy(Foo, {
      get(target, prop) {
        if (typeof target[prop] === 'undefined') {
          return '6' + prop;
        }
        return target[prop];
      },
    });
    
    console.log(foo.a);
    console.log(foo.b);
    console.log(foo.c);
    console.log(foo.d);