JavaScript Class Template for Object Oriented People

JavaScript, being a dynamic language, does have all those Object Oriented Paradigms and following is the template that I use to write my JavaScript classes.

function MyClass() { // MyClass = function() won’t work

var p = “”;

function a() {
alert( p );
};

//
MyClass.prototype.test = function( s ){
p = s;
a()
};

}; // End of Class: MyClass //

Usage of MyClass:


var x = new MyClass();
x.test("Hello World!");

As you can note, we have a public method: test(), a private method a() and also, a private variable: p.

Here is another interesting syntactic sugar for writing a public method:

function MyClass() { // MyClass = function() won’t work

var method=MyClass.prototype;

....
....

method.test = function( s ){
p = s;
a()
};
....
}

So, what is stopping us from writing JavaScript the OO way?