skip to Main Content

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


  1. 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.

    class Foo {
        static calculate(x) {
            if (x % 2 === 0) {
                return x / 2;
            } else {
                return x * 3 + 1;
            }
        }
    }
    
    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search