JavaScript: private classes

The concept behind the implementation of private classes in JavaScript is the same as the actual implementation of private members. JavaScript has no concept of the traditional OOP visibility keywords but honors the scope visibility. So if you have a class created with the traditional constructor pattern containing some variables inside, then those variable won't be accessible from outside the class. If you want to get their values, you have to declare a getter:

function Class() {

   var privateProperty = 'Test';

   this.getPrivateProperty = function() {

       return privateProperty;

   }

}

This is possible because our getter has still access to variables declared within the constructor body.
For the same reason, you can declare private classes in this way:

function Class() {

    var Class2 = {
		property: 'Test',
		method: function() {
			return this.property;
		}
	};

    this.get = function() {

    	var i;

    	for(i in Class2) {

    	   if(typeof Class2[i] === 'function') {

    	       alert(Class2[i]());

    	   }

    	}

    }

}

A simple test:

window.onload = function() {

    var myClass = new Class();
    myClass.get();

};

You can see this test below.

Test

Live test

Comments are closed.