Get Programming with JavaScript - Listing 9.05

Listing 9.05 - Including a moons array in our Planet constructor

var Planet = function (name, position, type) { this.name = name; this.position = position; this.type = type; this.moons = []; this.showPlanet = function () { var info = this.name + ": planet " + this.position; info += " - " + this.type; console.log(info); console.log("Moons: " + this.moons.join(', ') + "."); }; this.addMoon = function (moon) { this.moons.push(moon); }; }; var planet = new Planet( "Jupiter", 5, "Gas Giant" ); planet.addMoon("Io"); planet.addMoon("Europa"); planet.showPlanet();

Further Adventures

Listing 9.05 - Including a moons array in our Planet constructor - Tasks 1, 2 & 3

var Planet = function (name, position, type) { this.name = name; this.position = position; this.type = type; this.moons = []; this.showPlanet = function () { var info = this.name + ": planet " + this.position; info += " - " + this.type; console.log(info); console.log("Moons: " + this.moons.join(', ') + "."); }; this.addMoon = function (moon) { this.moons.push(moon); }; }; var planet = new Planet( "Jupiter", 5, "Gas Giant" ); planet.addMoon("Io"); planet.addMoon("Europa"); planet.showPlanet(); // create a second planet var planet2 = new Planet( "Barxon", 3, "Cheese Giant" ); // add three moons planet2.addMoon("Cheddax"); planet2.addMoon("Filboid"); planet2.addMoon("Studge"); // display the planet planet2.showPlanet();

Listing 9.05 - Including a moons array in our Planet constructor - Task 4

var Planet = function (name, position, type) { this.name = name; this.position = position; this.type = type; this.moons = []; this.showPlanet = function () { var info = this.name + ": planet " + this.position; info += " - " + this.type; console.log(info); console.log("Moons: " + this.moons.join(', ') + "."); }; this.addMoon = function (moon) { this.moons.push(moon); }; // add the new method this.removeMoon = function () { this.moons.pop(); }; };