Classes

Classes are special functions for creating objects.

Essential:

github.com/getify/You-Dont-Know-JS

Description:

We could say that JavaScript is a prototype-based language. The creation and behavior of objects are based on prototypes that are objects themselves. Compared to other class-based languages, JavaScript doesn’t have any class system and relies on objects. With the addition of classes in JavaScript, it’s now possible to use more traditional class creation and inheritance. Classes are templates for objects. You assemble a single template which is used to create various objects.

Table of Contents

  1. 1. Constructor
  2. 2. Extending
  3. 3. Public and Private
  4. 4. Documentation
  5. 5. Related notes

new

The new operator creates an instance of a user-defined object type or of one of the built-in object types that have a constructor function. When a function is invoked with new in front of it, we call it a constructor call. It will:

    ▪ create a new object,

    ▪ the object is [[Prototype]]-linked to the function,

    ▪ the returned object is set as the this binding for that function call and

    ▪ unless the function returns its own alternate object, the new-invoked function call will automatically return the newly constructed object.

Example:


1. Constructor

The constructor method is a special field for initializing an object created with a class.

Example:


2. Extending

Using the extend keyword, a class can extend another class. This removes the need to rewrite functionality you want to use across multiple classes.

Example:


3. Public and Private

Fields are public by default. Prefixing a field with a # will make them private. Private fields can only be accessed within the class:

Example:


4. Documentation

As usual, don’t forget to check MDN Web Docs in order to get a better understanding of classes, as well as many other JavaScript aspects.


All Notes: