Classes in Javascript

Asked

Viewed 79 times

6

I was researching about creating Javascript classes and noticed the example below:

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    
    return Greeter;
}());

var greeter = new Greeter("world");

Does anyone know why they use a self-executable function instead of just:

function Greeter(message) {
    this.greeting = message;
}

Greeter.prototype.greet = function () {
    return "Hello, " + this.greeting;
};
      
var greeter = new Greeter("world");

1 answer

2


The reason is organization and ease of code reading.

There is another possibility, which is not present in your code, which is to create "private methods", ie methods that the class can use internally but are not available outside the class. In that case have a IIFE is useful. An example could be:

var Greeter = (function() {
  var registados = 0;

  function magia(str) {
    return str.replace('Hello', 'Olá');
  }

  function Greeter(message) {

    this.greeting = message;
  }

  Greeter.prototype.greet = function() {
    return magia("Hello, " + this.greeting);
  };

  return Greeter;
}());

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

It is often said "writes code that is easy to delete", this because often the code evolves over time and we need to erase things etc. This way of writing, with everything concerning that encapsulated class within the IIFE creates organized code and it is easy to see what is related to the class if you need to move that class to another place or "refactor" the code.

Nowadays, with classes ES6 we can simply do:

class Greeter {
  constructor(message) {
    this.greeting = message;
  }

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

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

which is the way to organize with ES6 syntax.

Browser other questions tagged

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