Execution order of initializers and constructors in the class hierarchy
What is the order that decorator initilization functions and constructors will execute? Especially with regards to the inheritance hierarchy.
To clarify:
I tend to work with classes and instances that are frozen. After a class is defined, I will freeze its prototype and constructor. And then, when an instance is created, I will freeze that instance. This ensures that the instances are fairly predictable to work with.
However, I occasionally want to bind functions on the instance. While this is doable for a base class:
```
const A = freeze(class A {
#bar = 'bar';
constructor () {
this.foo = this.foo.bind(this);
Object.freeze(this);
}
foo () {
return this.#bar;
}
});
```
It falls apart the moment we have a class with a super class that freezes the instance
```
const B = freeze(class B extends A {
#baz = 'baz';
constructor () {
super();
this.m = this.m.bind(this);
Object.freeze(this);
}
m () {
return this.#baz;
}
});
```
Trying to construct an instance of `B` will fail, because the instance has already been frozen in `A`'s constructor, so setting `m()` on the instance is not possible.
Would a `@bound` decorator be able to solve this? I suspect the answer depends on whether all of the decorator initializers execute before any of the constructors, but I am uncertain what that execution order is.
1 条评论