Javascript classes

5

I was researching about creating classes in Javascript and I realized 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 the reason for using a self-executing function instead of just:

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

Greeter.prototype.greet = function () {
    return "Hello, " + this.greeting;
};
      
var greeter = new Greeter("world");
    
asked by anonymous 20.05.2017 / 13:25

1 answer

2

The reason is organization and ease of reading code.

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 which are not available outside the class. In this case having 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());

"write code that is easy to delete" , this is because often the code evolves over time and we need to delete things etc. This way of writing, with everything concerning this 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 site or "refactor" the code.

Nowadays, with ES6 classes 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());

This is the way to organize with ES6 syntax.

    
20.05.2017 / 13:43