Wednesday, February 23, 2011

JavaScript Closures: Used for Privacy

I mentioned in class how you could use closures to create private variables, just like Java has. The code below shows how this is done. Notice that the only way to get at joe's name is using the given functions. If you wanted to make the name a constant then you could just get rid of setName and no one would be able to change joe's name. Pretty cool!

//This is how you make an object with private variables.
function Employee(){};

function newEmployee(theName) {
 var name = theName;
 Employee.prototype.getName = function(){return name;}
 Employee.prototype.setName = function(n){name = n;}
 return new Employee();
}

//The only way to change joe's name is by calling joe.setName.
joe = newEmployee('Joe');
joe.getName(); //get his name
joe.setName('bob'); //he is now bob

You don't need the name variable, we could have just used theName instead. But, maybe this makes it clearer? I find it a bit more intuitive this way.

No comments:

Post a Comment