1 post tagged variable

JavaScript Module pattern - overused, dangerous and bloody annoying

The Module Pattern is a way of using a closure in JavaScript to create private variables and functions. Here's a brief recap:

var myObject = (function() {
//these are only accessible internally
var privateVar = 'this is private';
var privateFunction = function() {
return "this is also private";
};

return {
//these can be accessed externally
publicVar: 'this is public',

publicFunction: function() {
return "this is also public"
},

//this is a 'privileged' function - it can access the internal private vars
myFunction: function() {
return privateVar;
}
};
})();

myObject.privateVar; //returns null as private var is private
myObject.myFunction(); //return the private var as myFunction has access to private properties

Breaking this down, we create a function which is executed immediately (via the brackets at the end) and returns an object which gets assigned to myObject.

Continue reading