Creating methods within the constructor is almost never a good option. A great utility of this notation is the ease of creating private variables, since the methods created in there will have their scope closed to the constructor method. Take an example:
class Greeter {
constructor(message) {
const greeting = message; // variavel privada
this.greet = () => {
return "Hello, " + greeting;
}
}
}
console.log(new Greeter("World").greet())
The downside of using this way is that every time you create an object from the class Greeter
, javascript will create all the methods again, causing a greater use of memory unnecessarily, and if you write the methods conventionally within the class, it can optimize this so that it doesn’t have multiple functions in memory that do exactly the same thing.
The conclusion is that if you have few instances of the class Greeter
and your code gets really better with private variables, use, otherwise don’t use. :)
I’ve never seen put the methods inside the builder. Where did you see this?
– Woss