Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.7Objects in JavaScript

Part 3.7Objects in JavaScript

Objects are a big thing in programming. They are essential in an object oriented programming (OOP) and they are built to abstract from long lines of procedural code.

JavaScript supports the concept of objects.

Defining an object

The first way of defining an object is the clearest and easiest to understand and follows a syntax similar to other languages.

Using the new Object() keyword combination is similar to other languages:

JavaScript
var pet = new Object();

The next step is to give the object some values:

JavaScript
//Pet object
var gismo = new Object();
gismo.name = "Gismo";
gismo.type = "Cat";
gismo.dob = "10/03/1998";

var petro = new Object();
petro.name = "Petro";
petro.type = "Rabbit";
petro.dob = "29/04/2007";

These values within the objects can then be accessed using the same method as setting the values:

JavaScript
//Pet object
var petro = new Object();
petro.dob = "29/04/2007";
alert(petro.dob);

Using the object initialiser

The previous method of creating objects is just one way of doing this. An alternative is to use the object initialiser syntax, which is similar to the C++ method of creating objects.

The previous pet example could be simplified to:

JavaScript
//Pet object
var gismo = {
  name : "Gismo",
  type : "Cat",
  dob : "10/03/1998"
};

//Pet object
var petro = {
  name : "Petro",
  type : "Rabbit",
  dob : "29/04/2007"
};

Using the object initialiser can also be used to create arrays.

Inner values (properties) can still be accessed the same way:

JavaScript
//Pet object
var petro = {
  name : "Petro",
  type : "Rabbit",
  dob : "29/04/2007"
};
alert(petro.dob);

Creating with a constructor

The third method of creating an object in JavaScript is with a constructor function. A constructor is a method that is normally called when the object is created.

The this keyword refers to the object that the code is executed within. JavaScript differs from many languages in that the function becomes the context for the this keyword. This allows code to execute in a function like an object:

JavaScript
//Pet object
function Pet(name, type, dob){
  this.name = name;
  this.type = type;
  this.dob = dob;

  return this;
}

var petro = new Pet("Petro", "Rabbit", "29/04/2007");

alert(petro.dob);

That's all there is to objects. JavaScript objects can be used to mimic real world objects just as shown above.

Feedback 👍
Comments are sent via email to me.