Object-oriented (OO) JavaScript syntax is a bit convoluted for those coming from other OO languages.  Feel free to use this template to get you started.  To understand what’s going on, do a web search for JavaScript and the following keywords:

  • OO JavaScript
  • Object Literals
  • Anonymous Functions
  • Module Pattern
  • JSON
  • Douglas Crockford
  • Fleischkuekle
var MyClass = function(str) {

 	/* Private Stuff (Old-Skool Style) */
 	var aPrivateString = str;
 	var aPrivateArray = new Array();

 	function myPrivateMethod1() {

 		/* Access private field (above) */
 		aPrivateArray.push(str);

 		/* Access public field (below) */
 		publicCode.aPublicString = "slammy";

 		/* Access public method (below) w/private field
                   as arg (above) */
 		publicCode.myPublicMethod1(aPrivateString);
 	}

 	function myPrivateMethod2() {
 		alert("This is private method 2");
 	}

 	/* Public Stuff (Object Literal Style) */
 	var publicCode = {

 		aPublicString : "",
 		aPublicArray : [],  /* Note: JSON style */

 		/* Make private method publicly accessible */
 		accessPrivateMethod2 : myPrivateMethod2, 

 		myPublicMethod1 : function(str) {

 			/* Access a private field from above */
 			aPrivateString = str;

 			/* Access a private method from above */
 			myPrivateMethod1();

 			/* Access public variable from above
                           w/this keyword */
 			this.aPublicString = str;
 		},

 		myPublicMethod2 : function() {
 			alert(aPrivateString);
 		}
 	}

 	/* Return the public object literal code only */
 	return publicCode;
 }

 /* Client code demonstration */
 var myObj1 = MyClass('somestring');
 myObj1.myPublicMethod2();  // Allowed
 myObj1.aPublicArray.push('fleischkuekle'); // Access public field
 var myObj2 = MyClass('someotherstring');
 myObj2.myPublicMethod2(); // New instance means data is unique
 myObj2.accessPrivateMethod2(); // Allowed
 myObj2.myPrivateMethod2(); // Not allowed

The MyClass variable is assigned an anonymous function. The function encapsulates the code; therefore, all of the code inside of it is private (just make sure to use the var keyword to prevent the inner fields from being global). If you want any of the inner code to be public, then define it in an object literal, like publicCode, and return it to the caller. Some examples I have seen skip assigning the object literal to a variable, but rather define it in a return{} block instead. Either way works just fine.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)