I am trying to use property initializers to use arrow functions as methods of a class. But they are not accessible until the method is declared. If i change the order in which they are declared it works.
Is it expected behaviour or is it a babel transpilation
class SampleClass1 {
method2 = this.method1();
method1() {
return "works";
}
}
console.log((new SampleClass1()).method2); // Works
class SampleClass2 {
method2 = this.method1();
method1 = () => {
return "works";
}
}
console.log((new SampleClass2()).method2); // Error
Following url is a babel repl instance with the code i want to demonstrate please refer to it.
Yes, this is expected behaviour. Remember that the syntax from this ESnext proposal draft basically desugars to
class SampleClass1 {
constructor() {
this.method2 = this.method1();
}
method1() {
return "works";
}
}
class SampleClass2 {
constructor() {
this.method2 = this.method1();
this.method1 = () => {
return "works";
}
}
}
And it's obvious that you can call prototype methods from the constructor, but not methods on instance properties that you haven't yet created.