They do the same thing.
Defining the property outside the constructor is new class field syntax. If you need to support older browsers, either use the constructor method, or use Babel to transpile the code first down to older syntax.
Note that class fields run before the constructor finishes - either right after the super
call, if there is one, or at the very beginning of the constructor.
class Foo {
prop = console.log('Class field running');
constructor() {
this.prop2 = console.log('Constructor running');
}
}
const foo = new Foo();
Related: Private fields (also very new syntax) must be initialized outside of the constructor, so that the class can understand which fields are private at compile time:
class Foo {
constructor() {
this.bar = 1;
// Not OK:
// this.#foo = 1;
}
// OK:
#baz = 1;
}
const foo = new Foo();