/**
* This is a class called MyClass.
* Construct it with: var c = new MyClass(someInitValue);
*/
function MyClass(someInitValue) {
/** Public member variable. */
this.var1 = 0;
/** Private member variable (not visible to public member functions, though). */
var var2 = 42;
/**
* Use "that" in private functions when you need
* "this" functionality. It's a workaround.
*/
var that = this;
// Constructor functionality.
if(someInitValue < 0)
this.var1 = 0;
else
this.var1 = someInitValue;
/** Private member function, not visible to the outside. */
function getVar2() {
// Use "that" instead of "this" here.
return var2;
}
/**
* Privileged member function, visible to the outside
* but with access to private members (variables or functions).
*/
this.getVar2Priv = function() {
// Functions/variables you access must be defined before this function.
return getVar2();
};
}
/** Public member variable which will initialize in subclasses, too. */
MyClass.prototype.var3 = "Some value";
/**
* Public member function.
*/
MyClass.prototype.getVar1 = function() {
// We don't have access to private variable var2 from here.
return this.var1;
};
/**
* Static function. Call with MyClass.hello().
*/
MyClass.hello = function() {
alert("Hello, world!");
};
/**
* This is a class called ChildClass which is derived from MyClass.
*/
function ChildClass(childInitValue) {
// Call super-constructor.
MyClass.call(this,childInitValue);
}
ChildClass.prototype = Object.create(MyClass.prototype);
ChildClass.prototype.constructor = ChildClass;
/**
* Public child member function which uses function in super-class.
*/
ChildClass.prototype.getMultipleVar1 = function(n) {
var retVal = "", index;
for(index=0;index<n;index++)
retVal += MyClass.prototype.getVar1.call(this) + " ";
return retVal;
};