Menu

Object-oriented Programming in JavaScript (Part 1)

First published on: 8 Dec 2017
Prototypal Inheritance

This is the beginning of a series of short stories on Object-oriented Programming in JavaScript. The aim of this series, is to be a concise and handy reference for key concepts of object-oriented programming in JavaScript.

Objects and Properties

A property is a string with the key or property name separated by a colon and then the property value. An example of a property would be:

key: 'value'

This is an example of an object with its properties:

{
  key: 'value',
  propertyName: 1,
  property_name: {
    key: 'property value'
  }
}

Note, that numbers and types other than strings can be added as values. Also, note that property names/keys can be either camelcase or use underscores, there doesn’t seem to be a standard for this. Keys/property names are actually strings.

Object Literals

To create an object you can use object literal notation. An object literal looks like this:

var exampleObject = {
  keyOne: 'valueOne',
  keyTwo: 'valueTwo'
}

You can use a loop to create more objects like this. Alternatively, you can use object constructors.

Object Constructors

This is what an object constructor looks like:

function Pet (name, ageInYears) {
  this.name = name
  this.ageInYears = ageInYears
  this.notification = function () {
    return this.name + ' is ' + this.ageInYears + ' years old.'
  }
}

To create objects from the object constructor/function Pet add the new keyword:

var pet1 = new Pet('Dog', 4)
var pet2 = new Pet('Cat', 2)

Note that each time we create objects in this way, we are defining the notification function, which is not ideal. We can define functions on the prototype (these functions are called methods) instead.

So instead of:

function Pet (name, ageInYears) {
  this.name = name
  this.ageInYears = ageInYears
  this.notification = function () {
    return this.name + ' is ' + this.ageInYears + ' years old.'
  }
}

We do:

function Pet (name, ageInYears) {
  this.name = name
  this.ageInYears = ageInYears
}

Pet.prototype.notification = function () {
  return this.name + ' is ' + this.ageInYears + ' years old.'
}

Deciding which to use

Every time you use an object literal to create objects in a loop and there are functions in it, you are defining a function each time you create an object, which is not ideal. This is when you would use object constructors. Object literals seem easier to work with, and I often use them a lot for projects which don’t need methods and object constructors.

In the next part of the series, we will go over the this keyword:

Object-oriented Programming in JavaScript (Part 2)

The first version of this article was originally published on medium:

https://medium.com/@wlwlz/object-oriented-programming-in-javascript-part-1-683bbfb7c89

References: