Showing posts with label class. Show all posts
Showing posts with label class. Show all posts

Friday, 9 December 2011

Some useful classes

Cookie class

function Coockie(){
 this.create = function(name,value,days) {
  days = days || 999999;
  if (days) {
   var date = new Date();
   date.setTime(date.getTime()+(days*24*60*60*1000));
   var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  this.coockie_cache[name] = value;
  document.cookie = name+"="+value+expires+"; path=/";
 }

 this.read = function(name) {
  if(this.coockie_cache[name]) return this.coockie_cache[name];
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
   var c = ca[i];
   while (c.charAt(0)==' ') c = c.substring(1,c.length);
   if (c.indexOf(nameEQ) == 0) return this.coockie_cache[name] = c.substring(nameEQ.length,c.length);
  }
  return null;
 }

 this.eraseCookie = function(name) {
  createCookie(name,"",-1);
 }

 this.coockie_cache = {};
}
fireBug debug times class

var Debug = function(o){
 if('time' in console){
  if(Debug.times.length>0) console.timeEnd(Debug.times[Debug.times.length-1].name);
  Debug.times.push({name:o});
  console.time(o);
 }
}
Debug.times = [];
Debug.stop=function(){
 if('time' in console){
  for(var i=0;i< Debug.times.length-1;i++){
   Debug.times[i].total = console.timeEnd(Debug.times[i].name);
  }
  for(var i=0;i< Debug.times.length-1;i++){
   //log(Debug.times[i].name+": "+(Debug.times[i].total-Debug.times[i+1].total))
   //Debug.times[i].total = console.timeEnd(Debug.times[i].name);
  }
 }
};
js date week functions for date object

Date.prototype.getWeek = function () {  
    // Create a copy of this date object  
    var target  = new Date(this.valueOf());  
  
    // ISO week date weeks start on monday  
    // so correct the day number  
    var dayNr   = (this.getDay() + 6) % 7;  
  
    // ISO 8601 states that week 1 is the week  
    // with the first thursday of that year.  
    // Set the target date to the thursday in the target week  
    target.setDate(target.getDate() - dayNr + 3);  
  
    // Store the millisecond value of the target date  
    var firstThursday = target.valueOf();  
  
    // Set the target to the first thursday of the year  
    // First set the target to january first  
    target.setMonth(0, 1);  
    // Not a thursday? Correct the date to the next thursday  
    if (target.getDay() != 4) {  
        target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);  
    }  
  
    // The weeknumber is the number of weeks between the   
    // first thursday of the year and the thursday in the target week  
    return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000  
} 

Date.prototype.getWeekYear = function ()   
{  
    // Create a new date object for the thursday of this week  
    var target  = new Date(this.valueOf());  
    target.setDate(target.getDate() - ((this.getDay() + 6) % 7) + 3);  
    return target.getFullYear();  
}

Date.prototype.addDays = function(nr_of_days){
 var a = new Date(this.valueOf());;
 return nr_of_days==0?this:new Date(a.setDate(a.getDate()+nr_of_days));
}
Date.prototype.addDaysToSunday = function(){
 return this.addDays(
  7 - (this.getDay()==0?7:this.getDay())
 );
}
Date.prototype.moveToStartOfNextWeek = function(){
 return this.addDays(
  8 - (this.getDay()==0?7:this.getDay())
 );
}
Date.prototype.addWeeks = function(weeks){
 if(weeks<1) return this;
 return this.addDays(
  8 - (this.getDay()==0?7:this.getDay()) + 7*(weeks-1)
 );
}
Date.prototype.getISODay = function(){
 // Native JS method - Sunday is 0, monday is 1 etc.
 var d = this.getDay();
 // Return d if not sunday; otherwise return 7
 return d ? d : 7;
};

Date.prototype.getMaxWeekOfYear = function (){
 var year = this.getFullYear();
 var maxWeek = 52;
 fj = new Date(year, 0, 1); //1st Jan
 tfd = new Date(year, 11, 31); //31st Dec
 if(fj.getDay() == 4 || tfd.getDay() == 4){
  maxWeek = 53;
 }
 return maxWeek;
}

Sunday, 25 September 2011

JS Classes


First step(Basic class definition)

  • private variables are declared with the 'var' keyword inside the object, and can only be accessed by private functions and privileged methods.
  • private functions are declared inline inside the object's constructor (or alternatively may be defined via var functionName=function(){...}) and may only be called by privileged methods (including the object's constructor).
  • privileged methods are declared with this.methodName=function(){...} and may invoked by code external to the object.
  • public properties are declared with this.variableName and may be read/written from outside the object.
  • public methods are defined by Classname.prototype.methodName = function(){...} and may be called from outside the object.
  • prototype properties are defined by Classname.prototype.propertyName = someValue
  • static properties are defined by Classname.propertyName = someValue
function Mammal(name){
	//private var
	var id;
	//private method
	var set_id = function(){
		id = Mammal.id++;
	}
	//public property
	this.name=name;
	this.offspring=[];
	//privileged method
	this.getId = function(){
		return id;
	}
	//constructor
	set_id();
}
//public methods
Mammal.prototype.haveABaby=function(){ 
	var newBaby=new Mammal("Baby "+this.name);
	this.offspring.push(newBaby);
	return newBaby;
} 
Mammal.prototype.toString=function(){ 
	return '[Mammal "'+this.name+'"]';
}
//static property
Mammal.id = 1;

Second step(Inheritance)

  • You cause a class to inherit using ChildClassName.prototype = newParentClass();.
  • You need to remember to reset the constructor property for the class using ChildClassName.prototype.constructor=ChildClassName.
  • You can call ancestor class methods which your child class has overridden using the Function.call() method.
  • Javascript does not support protected methods .

Cat.prototype = new Mammal();        // Here's where the inheritance occurs 
Cat.prototype.constructor=Cat;       // Otherwise instances of Cat would have a constructor of Mammal 
function Cat(name){ 
	this.name=name;
} 
Cat.prototype.toString=function(){ 
	return '[Cat "'+this.name+'"]';
} 

var someAnimal = new Mammal('Mr. Biggles');
var myPet = new Cat('Felix');
alert('someAnimal is '+someAnimal);   // results in 'someAnimal is [Mammal "Mr. Biggles"]' 
alert('myPet is '+myPet);             // results in 'myPet is [Cat "Felix"]' 

myPet.haveABaby();                    // calls a method inherited from Mammal 
alert(myPet.offspring.length);        // shows that the cat has one baby now 
alert(myPet.offspring[0]);            // results in '[Mammal "Baby Felix"]' 

Using the .constructor property
Mammal.prototype.haveABaby=function(){ 
	var newBaby=new this.constructor("Baby "+this.name);
	this.offspring.push(newBaby);
	return newBaby;
} 
...
myPet.haveABaby();                    // Same as before: calls the method inherited from Mammal 
alert(myPet.offspring[0]); 

Calling 'super' methods

Cat.prototype.haveABaby=function(){ 
	Mammal.prototype.haveABaby.call(this);
	alert("mew!");
}

Making your own 'super' property

Cat.prototype = new Mammal();
Cat.prototype.constructor=Cat;
Cat.prototype.parent = Mammal.prototype;
...
Cat.prototype.haveABaby=function(){ 
	var theKitten = this.parent.haveABaby.call(this);
	alert("mew!");
	return theKitten;
} 

Spoofing pure virtual classes

LivingThing = { 
	beBorn : function(){ 
		this.alive=true;
	} 
} 
...
Mammal.prototype = LivingThing;
Mammal.prototype.parent = LivingThing;   //Note: not 'LivingThing.prototype' 
Mammal.prototype.haveABaby=function(){ 
	this.parent.beBorn.call(this);
	var newBaby=new this.constructor("Baby "+this.name);
	this.offspring.push(newBaby);
	return newBaby;
} 

Convenient Inheritance

Function.prototype.inheritsFrom = function( parentClassOrObject ){ 
	if ( parentClassOrObject.constructor == Function ) 
	{ 
		//Normal Inheritance 
		this.prototype = new parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject.prototype;
	} 
	else 
	{ 
		//Pure Virtual Inheritance 
		this.prototype = parentClassOrObject;
		this.prototype.constructor = this;
		this.prototype.parent = parentClassOrObject;
	} 
	return this;
} 
//
//
LivingThing = { 
	beBorn : function(){ 
		this.alive = true;
	} 
} 
//
//
function Mammal(name){ 
	this.name=name;
	this.offspring=[];
} 
Mammal.inheritsFrom( LivingThing );
Mammal.prototype.haveABaby=function(){ 
	this.parent.beBorn.call(this);
	var newBaby = new this.constructor( "Baby " + this.name );
	this.offspring.push(newBaby);
	return newBaby;
} 
//
//
function Cat( name ){ 
	this.name=name;
} 
Cat.inheritsFrom( Mammal );
Cat.prototype.haveABaby=function(){ 
	var theKitten = this.parent.haveABaby.call(this);
	alert("mew!");
	return theKitten;
} 
Cat.prototype.toString=function(){ 
	return '[Cat "'+this.name+'"]';
} 
//
//
var felix = new Cat( "Felix" );
var kitten = felix.haveABaby( ); // mew! 
alert( kitten );                 // [Cat "Baby Felix"]