JavaScript: A private member variable design pattern

JavaScript does not include some of the common features of a class based language like Java or C++. Simple concepts such as private member variables are not available via in-built syntax. This can result in the global scope becoming littered with variables leading to name conflicts or variable corruption.

One feature JavaScript supports which makes it trivial to implement private member variables is closures. An example of a closure follows:

function HelloWorld() {
    var sMessage = "Hello World";

    this.go = function() {

An example of using the above and demonstration of the effect of the closure.

var hello = new HelloWorld();

console.log(hello.sMessage); // will be undefined.
hello.go(); // will print "Hello World"

That’s it. Very simple. The local variable defined in the “HelloWorld” function is only available within the scope of the function. Any locally defined variable is accessible to methods defined (or enclosed) within the function. Therefore, the method “go” has access to the variable “sMessage”. Resulting in the behavior of a private member variable.


Leave a Reply

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

You are commenting using your 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