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
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:
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