Javascript Classes & Objects (Object Oriented Programming) Tutorial

In this Javascript tutorial we learn how to group data and behavior into single entities called classes.

We cover what classes and their objects are, how to declare a class, create a new instance of a class and how to access the members of a class.

We also cover class expressions, how to declare and use them.


Object Oriented Programming is a difficult topic for new programmers to understand. It’s okay if this section of the course takes you longer to understand than the others.

Object Oriented Programming: Classes & Objects

A popular approach to solving problems in most programming languages, is objected oriented programming, or OOP for short.

Object oriented programming is when we treat both data and behavior as a single, reusable unit. We try to model our application after entities in the real world by using classes and objects.

What is a class

A class is a blueprint, or recipe for an object. A class defines what every instance of it should contain. As an example, let’s consider a pizza.

Every pizza has:

  • A base
  • A sauce
  • Cheese
  • Toppings

This is our recipe, our class for a pizza. Not every pizza (instance of our class) will have the same toppings, but it will have toppings.

Classes may contain attributes (properties), as well as methods (functions). As an example, let’s consider a database of users.

Every user has attributes like:

  • A name
  • An age
  • An address
  • A profile picture
  • An email
  • A password etc.

Every user has functionality available to them, like:

  • Change password
  • Upload profile picture
  • Add to cart
  • Logout etc.

We combine our attributes and functionality into this single entity, a class. Every instance of a user will follow the pattern set up in the class but with different attributes.

What is an object

When we use the term object, we’re referring to an instance of a class. A single pizza, or user, that was created from the class blueprint.

Consider an array, an array is a class. When we create an array, we’re actually creating an instance, or object, of the array class.

Once we’ve created an object, we have access to the properties and functions that Javascript has declared inside the array class. Like array.length or array.splice().

Example:
<script>

  // an object of the array class
  var shopping_list = ["Bread", "Milk"];

</script>

In the example above, we’ve created an instance of the array class, an object called shopping_list. Now that we have an object, we have access to its properties and methods.

Example:
<script>

  // an object of the array class
  var shopping_list = ["Bread", "Milk"];

  // using a property of the array class
  document.write("There are ", shopping_list.length, " items in the shopping list");

</script>

We can create as many instances of a class as we need, each with their own different values, and each having the array.length property.

How to create a class

To create a class we use the class keyword, followed by a unique name and a code block.

Syntax:
class ClassName {

  // properties
  // methods

}
Example:
<script>

  class Employee {

    // properties
    name = "Unknown";

    // methods
    walk() {
      document.write("Walking...");
    }

  }

</script>

In the example above, we declare a class called Employee, with one attribute and one method (function).

We should note two conventions typically used when naming classes:

  1. We name our classes in the singular. Instead of a class named Cars, we call it Car
  2. We use Pascal casing. The first letter of the name is uppercase and each new word in the name has its first letter in uppercase. We don’t separate words with underscores.

We don’t have to name our classes this way but it is a good convention to follow. Some enterprises may require you to follow conventions such as these, or their own. In this tutorial series we will be using this convention.

How to instantiate an object

To create an object instance of a class, we use the new keyword, followed by the name of the class and a pair of open and close parentheses. We assign the new instance of the class to a variable to be able to use it.

Syntax:
var object_name = new ClassName();

The parentheses are used with a class constructor, we we explain in more detail further along in this tutorial.

Example:
<script>

  class Person {

    // properties
    name = "Unknown";

    // methods
    walk() {
      document.write("Walking...");
    }

  }

// instantiate
var p1 = new Person();

</script>

In the example above we create a new object of the Person class called p1. The variable can now be used to access the properties and methods of the person class.

Unlike functions, classes need to be declared before they can be instantiated or used. The instantiation simply needs to be below the declaration to avoid errors.

How to access class properties & methods (members)

We access class properties or methods with dot notation. First we write the object name, followed by a dot operator ( . ) and the property or method we want to access.

Syntax:
object_name.property;

object_name.method();
Example:
<script>

  class Person {

    // attributes
    name = "Unknown";

    // methods
    walk() {
      document.write("Walking...");
    }

  }

// instantiate
var p1 = new Person();

// access method
p1.walk();

</script>

In the example above, we call the walk() method which prints a simple message to the page.

How to create and use class expressions

Similar to function expressions, we can declare class expressions. We also use variables to fetch the class, so the class itself is allowed to be either named or unnamed.

Syntax: unnamed class
var expression_name = class {

  // class body
}
Syntax: named class
var expression_name = class ClassName {

  // class body
}
Example:
<script>

  var person = class {

    // attributes
    name = "Unknown";

    // methods
    walk() {
      document.write("Walking...");
    }

  }

</script>

The example above produces the same result as the named declaration, earlier in the tutorial.

We can access a class expression by either instantiating it directly with the new keyword, or by assigning it to a variable (thereby creating an object).

Example:
<script>

  var Person = class {

    // attributes
    name = "Unknown";

    // methods
    walk() {
      document.write("Walking...");
    }

  }

  new Person().walk();
  // or
  var p1 = new Person();
  p1.walk();

</script>

When we instantiate the class expression directly with the new keyword, we must remember to add open and close parentheses behind the expression_name. The parentheses are used to construct the object, if there is a constructor present in the declaration.

We cover constructors in a later tutorial.

When a class expression is named, we cannot use the class name to access its members. We must use the variable name.

Example:
<script>

  var Person = class Employee {

    // attributes
    name = "Unknown";

    // methods
    walk() {
      document.write("Walking...");
    }

  }

  // correct
  new Person().walk();

  // incorrect, will raise an error
  new Employee().walk();

</script>
Error:
Uncaught ReferenceError: Employee is not defined

Summary: Points to remember

  • A class in an entity that allows us to group both data and behavior into a single unit.
  • An object is an instance of the class blueprint. If a class is a cookie cutter, an object would be the cookie.
  • A class has to be declared at any stage above its invocation (use).
  • We instantiate a class by creating a new instance object.
  • We access the members of a class through dot notation, where the object name is followed by a dot and then the member we want to access.
  • We can declare class expressions with or without a name.
  • We can instantiate a class expression directly with the new keyword, or by creating an object.
  • When a class expression is named, we cannot use the name to invoke the class expression. Instead we must use the expression name.