Javascript Class Property Inside Vs Outside Constructor
Solution 1:
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.
classFoo {
prop = console.log('Class field running');
constructor() {
this.prop2 = console.log('Constructor running');
}
}
const foo = newFoo();
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:
classFoo {
constructor() {
this.bar = 1;
// Not OK:// this.#foo = 1;
}
// OK:
#baz = 1;
}
const foo = newFoo();
Solution 2:
Actually, defining this.bar
within the constructor is considered dirty code in ES6. You can expand any object by adding a property just the way you did. This is the way how it is done in ES5 and lower.
ES6 is mainly just syntactic sugar, meaning all you class definitions get boiled down to "native" JavaScript code. Behind the scenes, your definition of baz
will end up in the transcript exactly the way you defined bar
. However, for readability, the syntactic sugar was added in ES6 to define a property in a more class-like fashion.
Post a Comment for "Javascript Class Property Inside Vs Outside Constructor"