css

Friday, January 6, 2012

Javascript objects

I always wanted to create a simple example on how you can create objects in javascript. The example also contains private and public variables and functions.

/* Create a new object */
function testObject() 
{
 /* Private variables can only be called by functions inside this object */
 var privatePropertyValue = 'Private property:1';

 /* Public variables can be directly called through objectname */
 this.publicPropertyValue = 'Public property:1';
 this.objectName = 'testObject';


 /*
  Private functions can only be called by functions inside this object
  Private functions cannot directly access the this method of the object
 */

 function privateFunctionSetVariable() 
 {
  /* 
   Method this is not possible: e.g. 
   this.publicPropertyValue = 'Private function';
   does not refer to the object
  */
  alert("This will fail:" + this.objectName);
  privatePropertyValue = 'Private property:2';
 }

 function privateFunctionSetGlobalVariable(c) 
 {
  alert("This will succeed:" + c.objectName);
  c.publicPropertyValue = 'Public property:3';
 }


 /* Public functions can be directly called through objectname */
 this.publicFunctionSetVariable = function ()
 {
  this.publicPropertyValue = 'Public property:2';
 };

 this.publicCallPrivateFunction = function ()
 {
  privateFunctionSetVariable();
 };

 this.publicCallPrivateFunctionGlobal = function ()
 {
  privateFunctionSetGlobalVariable(this);
 };

 this.publicAlert = function (t,v)
 {
  if(t=='private') alert(eval(v));
  else alert(eval('this.'+ v));
 };

}


var createObject = new testObject();
createObject.publicAlert('public','publicPropertyValue');
createObject.publicFunctionSetVariable();
createObject.publicAlert('public','publicPropertyValue');
createObject.publicCallPrivateFunctionGlobal();
createObject.publicAlert('public','publicPropertyValue');


createObject.publicAlert('private','privatePropertyValue');
createObject.publicCallPrivateFunction();
createObject.publicAlert('private','privatePropertyValue');

No comments: