This is a common design pattern used in javascript programming where there is need for a getter and setter like functionality. It uses a self-invoking function to create a closure around it and then you can use getter and setter to access the properties.
Some advantages of use this approach:
- Concept of private and public properties and method’s is possible because of this.
- Your private variable are enclosed in the closure and it is not directly accessed from outside. So the chances of someone accidentally writing is not possible.
- Only way to change the properties on the object is by using the setter method.
- Implementation details of a function is hidden(Encapsulation) from the application that is using it.
var person = function() { var name;//local to this function. return { getName: function() { return name; }, setName: function(newName) { name = newName; } }; }(); alert(person.name); // Undefined alert(person.getName()); // "Undefined" person.setName("Sam Adams"); alert(person.getName()); // "Sam Adams"