Read the snippet of code below. Can you explain what is going on? How would you use this code to get the person's age?
// A person 'object'
var person = {};
// The person's date of birth (a date 'object')
person.dob = new Date("September 15, 1984");
// The person's age (a function of their date of birth)
person.age = function() {
// Today's date
var today = new Date();
// Time elapsed between today and date of birth, a simple calculation
var elapsed = today - this.dob;
// Time elapsed is expressed in milliseconds
// To return in years, we need to divide by the number of milliseconds in a year
// We use Math.floor to round this number down to the nearest whole number
return Math.floor(elapsed / (1000 * 60 * 60 * 24 * 365));
};
Now, try and extend the functionality of our person, by giving them the power of speech.
I've started this for you, have a go at filling in the missing piece:
// Let's empower this person with the ability to speak
person.say = function(something) {
// What goes here?
};
Have a go at extending the functionality of our person in other ways (a sleep
function perhaps?), or adding additional attributes, such as a name
.