Listing 9.02 - Adding methods to our constructed object
JS Bin
var buildPlanet = function (name, position, type) {
var planet = {};
planet.name = name;
planet.position = position;
planet.type = type;
planet.showPlanet = function () {
var info = planet.name;
info += ": planet " + planet.position;
info += " - " + planet.type;
console.log(info);
};
return planet;
};
var planet1 = buildPlanet(
"Jupiter",
5,
"Gas Giant"
);
planet1.showPlanet();
Listing 9.01 - Adding methods to our constructed object - Tasks 1&2
- Create a second planet. Use the buildPlanet function.
- Call the showPlanet method on your new planet.
var buildPlanet = function (name, position, type) {
var planet = {};
planet.name = name;
planet.position = position;
planet.type = type;
planet.showPlanet = function () {
var info = planet.name;
info += ": planet " + planet.position;
info += " - " + planet.type;
console.log(info);
};
return planet;
};
var planet1 = buildPlanet(
"Jupiter",
5,
"Gas Giant"
);
// build a second planet
var planet2 = buildPlanet(
"Neptune",
8,
"Ice Giant"
);
planet1.showPlanet();
// display the new planet
planet2.showPlanet();