Using Javascript Objects


var aquarium = {
Nemo : { type: "fish", species: "clownfish", length: 3.7 },
Dory: { type: "fish", species: "blue tang", length: 6.2 },
Bubbles: { type: "fish", species: "yellow tang", length: 5.6 },
Peach: { type: "echinoderm", species: "starfish", length: 5.3 },
"Coral Castle" : { type: "environment", material: "coquina", moves: false },

// function inside object is a method
addCritter: function( name, type, species, length){
    this[name] = {type: type, species: species, length: length};
},

// function inside object is a method
takeOut : function(name){
    // take the name and add it to the returned object
    this[name].name = name;
    var temp = this[name];
    delete this[name];
    return temp;
}
};

// aquarium object does not have a length
// aquaririum.length = undefined

// enumeration with the for-in loop
// the in keyword looks 'in' the object to its right
// it finds each enumerable property in turn
// similar to accessing each index of an array
// key can be replaced with any chosen identifier

var numFish = 0;
for(key in aquarium){
console.log(key);
if(aquarium[key].type=="fish"){
    numFish++;
}
}

console.log(numFish);

// can we put this inside the object?

aquarium.countFish = function(){
var numFish = 0;
for(key in this){
    if(this[key].type=="fish"){
        numFish++;
    }
}
return numFish;
}
console.log(aquarium.countFish());
var poorDory = aquarium.takeOut("Dory");
console.log(poorDory);
console.log(aquarium.countFish());
By Chris Armstrong
Monday 3rd March 2014

Comments

There are currently no comments

Make a comment