Get Programming with JavaScript - Listing 9.02

Listing 9.02 - Adding methods to our constructed object

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();

Further Adventures

Listing 9.01 - Adding methods to our constructed object - Tasks 1&2

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();