6.2 Using a constructor
In the previous section, we learned to create a single object using what is known as the literal notation. However, sometimes you may need to create several similar objects in your program. In cases like this, it is more convenient to use a function to first create a template of the object. We can then create multiple objects from this template. This template is known as an object constructor.
To create an object constructor for the previous example, add the following code to chap6.js:
function CarObject(make, model, year, color, sunRoof) { this.make = make; this.model = model; this.year = year; this.color = color; this.sunRoof = sunRoof; this.drive = function(speed) { console.log("Moving forward at " + speed + " mph"); }; }
Like any other functions, we create the object constructor using the function keyword. Notice however that we name the function CarObject. This practice of capitalizing the first letter of each word, including the first word, is known as PascalCasing. It is common to use PascalCasing when naming object constructors. This is the convention that we’ll be following on the site.
You may notice a strange word – this – in the object constructor above.
this is a keyword in Javascript. When used inside a constructor, it refers to the object that is being created. In the statement
this.make = make;
make on the left side of the statement refers to the property of the object created while make on the right side refers to the parameter.
Hence, the statement above essentially means – assign the value of the make parameter to the make property of the object that is being created (referred to as this).
To create an object(s) from the object constructor, we write
var petersCar = new CarObject('Honda', 'Civic', '2015', 'Blue', true); var johnsCar = new CarObject('Ford', 'Mustang', '2017', 'Black', false);
Try adding the 2 statements above to chap6.js. This creates two CarObject objects – petersCar and johnsCar.
We can now access the objects’ properties and methods using square brackets or dot notation. Add the code below to chap6.js:
console.log(johnsCar.make); petersCar.drive(80); johnsCar.drive(70);
You’ll get
Ford
Moving forward at 80 mph
Moving forward at 70 mph
as the output.