1

What's the difference between the two code snippets below. I understand that the second one uses IIFE, however I am unable to understand what's the benefit of one over other. Can you please explain.

//First*******
var student=function student(name) {
    this.name = name;
}
student.prototype.printMessage = function () {
    console.log(this.name);
};
var st = new student("test");
st.printMessage();

//Second**
var student = (function () {
function student(name) {
    this.name = name;
}
student.prototype.printMessage = function () {
    console.log(this.name);
};
return student;
}());
var st = new student("test");
st.printMessage();
Nirbhay Jha
  • 491
  • 5
  • 13

2 Answers2

0

In your simple example, there is no advantage to using the IIFE. The purpose of such a construction would be if you had variables other than student that you didn't want to expose to the global scope.

Web_Designer
  • 72,308
  • 93
  • 206
  • 262
0

The first one is a normal constructor pattern that you have stated

The second one which used an IIFE is using closures. It is used to make separate modules where each module has a constructor function having some properties

In the second pattern you can also make some properties private that you do not want to expose to the code outside the module

For further reference: Emulating private properties with closures

Rahul Arora
  • 4,503
  • 1
  • 16
  • 24