Just another JavaScript custom object example. With this one I create a global object variable that is referenced by my class through its prototype. In this way the could also be referenced by other classes and this allows me to maintain some datas independently of the code.


/**
 * This is an example JavaScript object/classes
 * 
 * @author Christopher Stoll
 * @version 1.0
 */

/**
 * Core beer data object
 */
var beerData = {
// major groups
beerGroups: {
g0: 'undefined',
g1: 'ale',
g2: 'lager'
},
// styles
beerStyles: {
s0:{id:0,group:0,name:''},
s1:{id:1,group:1,name:'American Ale'},
s2:{id:2,group:1,name:'American Pale Ale'},
s3:{id:3,group:1,name:'Holiday Ale'},
s4:{id:4,group:1,name:'Dortmunder Export'},
s5:{id:5,group:2,name:'Pilsner'}
},

// types
beerTypes: {
non:{id:0,
name:'',
style:0,
price:0.00},
pbr:{id:1,
name:'PBR',
style:1,
price:0.60},
snv:{id:2,
name:'Siera Nevada',
style:2,
price:1.25},
xal:{id:3,
name:'Christmas Ale',
style:3,
price:1.50},
hal:{id:4,
name:'Holiday Ale',
style:3,
price:1.00},
dgd:{id:5,
name:'Dortmunder Gold',
style:4,
price:1.25},
bud:{id:6,
name:'Budweiser',
style:5,
price:0.75}
}
};

/**
 * Beer constructor
 *
 * @constructor
 * @this {beer}
 * @param {beerData.beerTypes} ptype The beer type
 * @see {beerData}
 */
function beer(ptype, pbottles){
// beer style, default is none
this._type = ptype || this._data.beerTypes.non;
// number of bottles, default is 6
this.bottles = pbottles || 6;
}
// inherit data from beerData
beer.prototype._data = beerData;
/**
* set this beers type
*
* @this {beer}
* @param {string} ptype The beer name
* @return {boolean} Changed succesfully
*/
beer.prototype.setType = function(ptype){
var result = false;
for(var type in this._data.beerTypes){
if(this._data
.beerTypes[type].name == ptype){
this._type = 
this._data
.beerTypes[type];
result = true;
break;
}
}
return result;
}
/**
* get this beer's name
*
* @this {beer}
* @return {string} The beer's name
*/
beer.prototype.getName = function(){
return this._type.name;
}
/**
* get this beer's style
*
* @this {beer}
* @return {string} The beer's style
*/
beer.prototype.getStyle = function(){
return this._data
.beerStyles['s'+this._type.style]
.name;
}
/**
* get this beer's group
*
* @this {beer}
* @return {string} The beer's group
*/
beer.prototype.getGroup = function(){
return this._data
.beerGroups['g'+this._data
.beerStyles['s'+this._type.style]
.group];
}
/**
* get how much this beer costs
*
* @this {beer}
* @return {numeric} The beer's group
*/
beer.prototype.getCost = function(){
var result = this._type.price * this.bottles;
return result.toFixed(2);
}
var ab = new beer();
ab.setType('Christmas Ale');
var bb = new beer(ab._data.beerTypes.pbr);

Tags: Blogger JavaScript Object-oriented Code

Published: 2010-04-03