Class in JavaScript

JavaScript uses prototypal inheritance: every object inherits properties and methods from its prototype object.

The prototypal inheritance can emulate the classic class inheritance. To bring the traditional classes to JavaScript, ES2015 standard introduces the class syntax: a syntactic sugar over the prototypal inheritance.

What is a class

A class is a blueprint, or recipe for an object. A class defines what every instance of it should contain.

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.

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.

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.

Related Posts

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events…

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the…

What are the basic rules for JavaScript parameters?

A JavaScript function is a code that performs a particular task. The function parameters are the name list in the function definition. Parameters are also known as…

How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default…

Target a Window Using JavaScript or HTML

TARGET attribute of HTML A link’s opening named frame or window is specified using the Target attribute of the <a> anchor tag. The concluding </a> tag in…

What is the role of deferred scripts in JavaScript?

Since JavaScript is a loosely typed language, you are not required to correctly predict the kind of data that will be kept in a variable. Depending on the information…