Javascript objects are great. They are very flexible and easy to use. This blog attempts to provide a concise but clear description of how to use them. There are many facets of this topic that are not covered.
Grouping related elements into a single object:
x = {}; // creates empty object
x.max = 999;
x.min = -999;
x.verify = function(val) {
if(val < x.min || val > x.max) return false;
else return true;
}
var verified = x.verify(88);
Referencing a property of object x:
var prop = ‘max’;
x.max or x[‘max’] or x[prop] – all reference the same element
Iterating thru all the properties of object x:
for( prop in x ) {
alert( prop + ‘=’ + x[prop] );
}
Defining an object where multiple instances are needed:
function DataRec(recFields) {
this.recFields = recFields;
this.vals = [];
}
DataRec.prototype.get = function(fldName) {
var ndx = this.recFields[fldName];
return this.vals[ndx];
}
DataRec.prototype.set = function(fldName,val) {
var ndx = this.recFields[fldName];
this.vals[ndx] = val;
}
var carFields = {‘brand’:1, ‘model’:2, ‘mpg’:3};
var houseFields = {‘sqft’:1, ‘address’:2, ‘price’:3};
var carRecs = []; //array for holding instances of DataRec
carRecs[0] = new DataRec(carFields)); // *** instance of object created ***
carRecs[0].set(‘brand’,’Ford’); // sets vals[1] = ‘Ford’
Notes about the example shown above:
Vars carFields and houseFields are examples of another way to define an object.
DataRec function defines the object.
Each instance of the DataRec object will contain an array of values (.vals) and a pointer to an object (.recFields) defining the vals index for each field in the record (ex.vals[3] holds mpg value). Each DataRec instance contains only a reference to the recFields object, not a copy of the object itself.
The .get and .set methods were added using the prototype feature. Properties added this way are shared by all instances of the object. If these methods were defined inside the DataRec function, then each instance would contain the code.
Ciao