javascrip object constructor - javascript - Javascript object - javascript object destructor

Javascript Object Constructors — Building Blocks

All Javascript types are based internally on objects. These are essential to creating robust and maintainable software because they create a convenient “thing” that maps directly to the data and actions essential to the problem being solved, hide private internal working parts, and provide a conceptual framework that makes it easier to understand its operations.

The act of creating an object includes initializing its internal state, like the color of a bicycle object. These initializations are bundled together in special functions called constructors. (Before moving on, it might be worthwhile reviewing our blog entry on Javascript prototypes, the backbone of objects.)

This blog post will explore how the Javascript standard directs Javascript ES6 programmers to create object constructors.

Javascript Object Constructors Step-by-Step

Javascript objects encapsulate an idea into an easy-to-manipulate digital object. For example, consider how we think about cars: one way is to keep track of the make, model, and year of the vehicle.

function Car(make, model, year) {
// code goes here
}

In this case Car is a template or blueprint for creating multiple instances of cars. The function Car() is  an object constructor function. Best practices for Javascript object constructors are:

  • The new keyword must be used to instantiate an object.
  • Constructor names begin with a capital letter.

The constructor has three parts, two of which are done for you by Javascript: the assignment of this to the object address and returning this to the caller. What remains are the steps necessary to create a complete object representation. In the following example, the parameters passed into the constructor are copied to the object. (We could add computation to determine if the vehicle year is more than (say) 25 years old and then assign this.historical = true, or check the parameters against federal standards and set assign this.electric = true.)

function Car(make, model, year) {
  // this = {};  (set automagically)

  // robust code would include parameter sanity-checking
  this.make = make;
  this.model = model;
  this.year = year;

  // return this (done implicitly by Javascript)
}

Objects of type Car are created by calling Car() with the keyword new

let myCar = new Car( "Jeep", "Wrangler YJ", 1987 );

Examining the object immediately can be done as simply as: 

console.log(myCar);

The resulting output looks like this:

Car {
  make:"Jeep",
  model:"Wrangler YJ",
  year:1987
}

Adding Additional Properties to Objects

Javascript object constructors build out the standard definition of your object. They don’t proscribe adding additional properties to your objects. For example, consider the following lines of code:

let myCar = new Car( "Jeep", "Wrangler YJ", 1987 );
let yourCar = new Car( "Ford", "Taurus", 1992 );
yourCar.description = "Windshield wipers need work.";

Adding a property to one object doesn’t affect the other objects of that type.

console.log(myCar.description);
console.log(yourCar.description);

The output from the above, shown here, illustrates the independence of the objects.

undefined
Windshield wipers need work.

Adding Additional Methods to Objects

Methods are added to an individual object without affecting the other instances of that object type in the same way properties are.

myCar.backUpSound = function () {
  return "beep, beep, beep!";
};

console.log(myCar.backUpSound());
console.log(yourCar.backUpSound());
 
beep, beep, beep!
error: Uncaught TypeError: yourCar.backUpSound is not a function

To provide backUpSound() to all objects created in the future it must be added into the constructor, alongside the properties. Existing objects will need to be individually upgraded, as they’ve already been instantiated and the constructor didn’t then have the new function.

The following revision shows a Javascript object constructor that includes a property and function.

function Car2(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.reverseSound = "silence";
  this.backUpSound = function () { return this.reverseSound; }
}

Objects created from this new constructor have the ability to report on the property. In this way are objects refined and given new functionality. Existing objects do not inherit these new capabilities.

let myCar2 = new Car2( "Lotus", "Esprit", 2010 );
console.log(myCar2.backUpSound());

myCar2.reverseSound = "grind, grind, sputter!"
console.log(myCar2.backUpSound());

The output ought not be a surprise.

silence
grind, grind, sputter!

Javascript Object Destructors

Unlike some other languages, Javascript doesn’t have a corresponding destructor capability. Without going into a deep discussion about garbage collection (the scavenging of objects and returning their resources once they’re no longer used), suffice it to say that there’s an open proposal to add such to an upcoming version of Javascript.

For the moment, setting object values to null or using addWeakEventListener() may provide a similar functionality as would a dedicated destructor.

Conclusion

Javascript object constructors are the engine which assembles new objects. This blog entry covered the basics of constructors and how to add properties and functions to existing objects and into constructors, providing the framework for refining and enhancing objects over the software development lifecycle.

Start Learning

To learn more about Javascript, check out other Javascript blog posts and enroll in our Javascript Nanodegree programs, including Intermediate Javascript.

Source Code

Complete source code, when needed to expand upon the snippets above, will be included below, ready for use in an online Javascript tester like PlayCode.

function Car(make, model, year) {
  // this = {};  (set automagically)
  // copy values to `this`; robust code would include parameter sanity-checking
  this.make = make;
  this.model = model;
  this.year = year;
  // return this (done implicitly by Javascript)
}
 
let myCar = new Car( "Jeep", "Wrangler YJ", 1987 );
let yourCar = new Car( "Ford", "Taurus", 1992 );
yourCar.description = "Windshield wipers need work.";
 
console.log(myCar.description);
console.log(yourCar.description);
 
myCar.backUpSound = function () {
  return "beep, beep, beep!";
};
 
console.log(myCar.backUpSound());
console.log(yourCar.backUpSound());

function Car2(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.reverseSound = "silence";
  this.backUpSound = function () { return this.reverseSound; }
}
 
let myCar2 = new Car2( "Lotus", "Esprit", 2010 );
console.log(myCar2.backUpSound());
myCar2.reverseSound = "grind, grind, sputter!"
console.log(myCar2.backUpSound());