skip to Main Content

The name property of a JavaScript class constructor is read-only once the class is defined, but it can be modified by a static field definition in the class body itself. However, I was surprised to find that it can’t be modified in a static initialization block.

This works great:

class Foo {
  static name = 'Bar';
}

But this throws a TypeError saying that name is read-only:

class Foo {
  static {
    this.name = 'Bar';
  }
}

Is this the intended behavior or an accidental quirk in the spec?

2

Answers


  1. A static property declaration uses (internally) the Object.defineProperty() mechanism (well the internal version). Thus overriding the "name" property works there, because that won’t check "read-only" the way a normal property assignment does.

    Thus this will also work:

    class Foo {
      static {
        Object.defineProperty(this, "name", { value: 'Bar'});
      }
    }
    
    Login or Signup to reply.
  2. This piece of code will work just fine .The idea I suppose is that the static elements needs to be defined before you use the static initialization blocks.
    Read more here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks

      class Foo {
        static name ;
        static {
            this.name = 'Bar1';
          }
      }
      console.log(Foo.name)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search