Skip to content

JavaScript Functions in Objects

tdkehoe edited this page Jun 1, 2015 · 3 revisions

This program creates two plants, a rose and a pine. The user enters up to five parameters: type of plant, how many times you water the plant, how many times you feed the plant, how many times you pour anti-freeze on the plant (which kills the plant), and whether you put the plant in the sun.

var myPlant = {
    state: 'a seed',
    height: 0,
    typeOfPlant: null,
    flower: "doesn't have",

    care: function(type, water, food, antifreeze, sun) {
        myPlant.typeOfPlant = type;
        if (type === 'rose') {
            if (water > 0) { myPlant.state = 'alive' }
            if (water > 0) { myPlant.isPlant = true }
            if (water > 0) { myPlant.height = myPlant.height + (2 * water) }
            if (food > 0) { myPlant.height = myPlant.height + (1 * food) }
            if (myPlant.height > 12) {myPlant.height = 12}
            if (sun > 0) { myPlant.flower = "has" }
            if (antifreeze > 0) { myPlant.state = 'dead' }
            if (water > 4 && food > 4) { myPlant.state = 'dead' }
        }

        if (type === 'pine') {
            if (water > 0) { myPlant.state = 'alive' }
            if (water > 0) { myPlant.isPlant = true }
            if (water > 0) { myPlant.height = myPlant.height + (4 * water) }
            if (food > 0) { myPlant.height = myPlant.height + (2 * food) }
            if (antifreeze > 0) { myPlant.state = 'dead' }
        }
    }
};

myPlant.care('rose', 4, 4, 0, 1); // type, water, food, antifreeze, sun

console.log("My " + myPlant.typeOfPlant + " is " + myPlant.state + ".");
console.log("The height of my " + myPlant.typeOfPlant + " is " + myPlant.height + " inches.");
console.log("My " + myPlant.typeOfPlant + " " + myPlant.flower + " a flower.");

The "trick" is the chain the object name (myPlant) in front of the property names, e.g., myPlant.type. The parameters aren't chained to the object, e.g., water.

The parameters are created in the function: care: function(type, water, food, antifreeze, sun).

The parameters are passed into the object by calling the object and the property that is the function: myPlant.care, and then the parameters in parentheses, separated by commas.

The results are passed out of the object even though the variables are local, not global. (?)

Clone this wiki locally