UX Design and Development course

Adding methods to our objects

Constructor function

var car = function(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.ageOfCar = carAgeCalc; // no parens
};

Function (method) to calculate age

var carAgeCalc = function() {
  //var currentDate = new Date().getFullYear();
  var numYears = 2013 - this.year;
  return numYears;
};

Vars that contain the properties of the objects

var myCar = new car ("Toyota", "RAV4", 2003);
var wifeCar = new car ("Toyota", "Sienna", 2009);
var firstCar  = new car ("Ford", "Fiesta", 1988);

To write this out, let's add the following:

console.log("My " + myCar.make + " " + myCar.model + " is " + myCar.ageOfCar() + " years old.");
console.log("My " + wifeCar.make + " " + wifeCar.model + " is " + wifeCar.ageOfCar() + " years old.");
console.log("My " + firstCar.make + " " + firstCar.model + " is " + firstCar.ageOfCar() + " years old.");

Play with code

JS Bin