February 27, 2021

Answer to JavaScript Objects Exercise Q10

 

//constructor
function Mountain(aName, aHeight)
{
//properties
this.name = aName;
this.height = aHeight;
this.toString = getString;
}

function getString()
{
window.alert('The name of this mountain is ' + this.name + '\n'
+ 'The height is ' + this.height + ' metres');
}

//instantiate a Mountain object
var everest = new Mountain('Everest' , 8850);
/*
//display the values of each property
window.alert('The name of this mountain is ' + everest.name + '\n'
+ 'The height is ' + everest.height + ' metres');
*/

everest.toString();

/*
The following illustrates, for comparison with Q9,
how to create an array of objects, before
accessing the data held by each object
*/

var k2 = new Mountain('K2' , 8611);
var matterhorn = new Mountain('Matterhorn' , 4478);
var annapurna = new Mountain('Annapurna' , 8091);
var mountainArray = new Array(4);
//add the mountain objects to the array
mountainArray[0] = everest;
mountainArray[1] = k2;
mountainArray[2] = matterhorn;
mountainArray[3] = annapurna;
//now loop through the array and display each name and height.
for(var i=0; i<mountainArray.length; i=i+1)
{
   mountainArray[i].toString();
}

Notes:

  • The implementation of the toString() method in the constructor is achieved by assigning a function name to the method name
    this.toString = getString
    where getString is the name of the function following the constructor. You do not add the () brackets to either the method name or the function name in this line of code.
  • To use the toString() method you must employ the dot notation
    everest.toString();

 

Back « JavaScript objects exercise

 

 

 

 

 

 

 

 

Up to top of page