Listing 9.03 - An array of constructed objects
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 planets = [
buildPlanet( "Jupiter", 5, "Gas Giant" ),
buildPlanet( "Neptune", 8, "Ice Giant" ),
buildPlanet( "Mercury", 1, "Terrestrial" )
];
planets.forEach(function (planet) {
planet.showPlanet();
});
Listing 9.03 - An array of constructed objects - Tasks 1&3
- Add two more planets to the planets array.
- Add code to visually separate each planet from the next.
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;
info += "\n"; // A new-line character
console.log(info);
};
return planet;
};
var planets = [
buildPlanet( "Jupiter", 5, "Gas Giant" ),
buildPlanet( "Neptune", 8, "Ice Giant" ),
buildPlanet( "Mercury", 1, "Terrestrial" ),
buildPlanet( "Mars", 4, "Terrestrial" ),
buildPlanet( "Venus", 2, "Terrestrial" )
];
planets.forEach(function (planet) {
planet.showPlanet();
});