JavaScript Module Pattern

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.

Demo on jsfiddle

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"

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s