Private variables in javascript


In OOP we learned the importance of the encapsulation.
In java we could encapsulate a variable through the
keyword private, that says that variable is visible only in
that object.

In javascript we don’t have a specific keyword like that, but
there are different ways to accomplish this behavior.

In this post I’ll talk about two ways of doing that:

1- Declaring function scoped variables using var:

Let’s say we have an contructor function called User,
and this function defines that an user object will have the following
properties:

name, phone, email, password

We could see the constructor function below:

	function User(name, phone,email, pass){
		this.name = name;
		this.phone = phone;
		this.email = email;
		this.password = pass;
	}

With this constructor all those properties are visible outside the function as we
could see below:

	user = new User("John Doe","888-888-888","john@doe.com","pass123");
	console.log("Name:"+ user.name);
	console.log("Phone:"+ user.phone);
	console.log("Email:"+ user.email);
	console.log("Pass:"+ user.password);//do we really like this be available????

One of the ways we can make that property password be visible only for the function is using the var keyword:

	function User(name, phone,email, pass){
		this.name = name;
		this.phone = phone;
		this.email = email;
		var password = pass;
	}

	user = new User("John Doe","888-888-888","john@doe.com","pass123");
	console.log("Name:"+ user.name);
	console.log("Phone:"+ user.phone);
	console.log("Email:"+ user.email);
	console.log("Pass:"+ user.password);//undefined -- now we can't access that

And to make that property available we can have a public method that exposes or change the variable value

	function User(name, phone,email, pass){
		this.name = name;
		this.phone = phone;
		this.email = email;
		var password = pass;

		this.myPassword = function(){
			var protectedPass= '';
			for(var i=0,count = password.length; i< count; i++){				
                             protectedPass += "*";
			}
			return protectedPass ;
		}
	}

	user = new User("John Doe","888-888-888","john@doe.com","pass123");
	console.log("Name:"+ user.name);
	console.log("Phone:"+ user.phone);
	console.log("Email:"+ user.email);
	console.log("Pass:"+ user.password);//undefined -- now we can't access that
	console.log("Protected Password:" + user.myPassword());

2- Using Module Pattern

You can find a better description of the module pattern here:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript

It is another way to promote encapsulation using Javascript.

A simple module can be seen in the code below:


moduleTest = (function(){
	return {
		displayMessage: function(msg){
			console.log("Displaying Message: " + msg);
		}
	};
})();

moduleTest.displayMessage("Testing the module");

Now let us see how we can use the Module Pattern to create private variables.
So let’s create the user class using the Module Pattern:


User = (function(){
	var password = "";

	function changePassword(newPass){
		password = newPass;
	};

	return function(name,email,phone,pass){
		this.name = name;
		this.email = email;
		this.phone = phone;
		password = pass;
		this.showMyPassword= function(){
			console.log(password.replace(/./g,"*"))
		};

		this.newPassword = function(){
			changePassword("123passwordNew");
			console.log("Password Changed!!");
		};
	};
})();

user = new User("John Doe", "john@doe.com",888-888-888,"pass123");
user.showMyPassword();
user.newPassword();
user.showMyPassword();

Using this pattern, the variable password and the function changePassword are not visible
oustide the module, but they are visible to the returned function through closure.

These are some of the ways to create private variables in javascript,
the first one seems to be simpler than the second one. But I think the second one
more elegant than the first.

Using the var keyword in the constructor function we would make the function too much bloated.
But using the module pattern, we can declare the private variable and functions inside the module,
and expose through the returned function or object.

That’s it.
See you in the next post.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s