Javascript- Syntax of classes

Asked

Viewed 39 times

1

class Greeter {
   constructor(message) {
   this.greeting = message;
   /* this.greet = () => {
    return "Hello, " + this.greeting; --> Método dentro do construtor  */ 
}

greet() {
return "Hello, " + this.greeting;
  }
};

var greeter = new Greeter("world");
console.log(greeter.greet());

Does it have any difference or consequences of putting the methods inside the constructor or outside? Or is it mere convention of the galley?

  • I’ve never seen put the methods inside the builder. Where did you see this?

1 answer

0


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. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.