// Creating the class
var Person = function( p_options ){
// Private options used for construction
var options = {
name: null,
age: 0
};
/**
* Set the options if provided any.
* This options pattern is from Mootools, and thier library
* will do it for you for free!
*/
if ( p_options != null && p_options != undefined
&& p_options != 'undefined' ){
for ( var opt in options ) {
if ( p_options[ opt ] != null
&& p_options[ opt ] != undefined
&& p_options[ opt ] != 'undefined' ){
options[ opt ] = p_options[ opt ];
}
}
}
// Private name
var m_name = options.name;
// Private age
var m_age = options.age;
// Private method
var calcAgeInDogYears = function(){
return m_age / 7;
};
// Begin public section
return {
// Name acceesor
getName: function(){
return m_name;
},
// Name mutator
setName: function(name){
m_name = name;
},
// Age accessor
getAge: function(){
return m_age;
},
// Age mutator
setAge: function(age){
m_age = age;
},
// Get person's age in dog years
getAgeInDogYears: function(){
return calcAgeInDogYears();
}
};
};
// Testing 'options' pattern and constructor regular
var dave = new Person({ name: "David Smith", age: 24 });
// Testing 1 parameter version (should use default for age)
var john = new Person({ name: "John Doe" });
// Should use defaults for name and age
var fred = new Person();
// Testing accessors
// Expected: normal
alert("Name: " + dave.getName() + "\nAge: " + dave.getAge());
// Expected normal name + 0 age
alert("Name: " + john.getName() + "\nAge: " + john.getAge());
// Expected: null name and 0 age
alert("Name: " + fred.getName() + "\nAge: " + fred.getAge());
// Testing mutators
fred.setName( "Fred Flinstone" );
fred.setAge( 45 );
// Expected: name = yabba dabba do + age = 45
alert("Name: " + fred.getName() + "\nAge: " + fred.getAge());
// Testing public calls to private methods
alert("Name: " + fred.getName() + "\nAge In Dog Years: "
+ fred.getAgeInDogYears());