Classes ES6 Flashcards

1
Q

What is a class?

A

Classes are basically a compact syntax for setting up prototype chains.

Note that we don’t need classes to create objects. We can also do so via object literals. That’s why the singleton pattern isn’t needed in JavaScript and classes are used less than in many other languages that have them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the class body?

A

The body of a class is the part that is in curly braces {}. This is where you define class members, such as methods or constructor.

The body of a class is executed in strict mode even without the "use strict" directive.

A class element can be characterized by three aspects:

  • Kind: Getter, setter, method, or field
  • Location: Static or instance
  • Visibility: Public or private

“Class body” (MDN Web Docs). Retrieved November 11, 2024.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the class constructor?

A

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name “constructor” in a class — a SyntaxError is thrown if the class contains more than one occurrence of a constructor method.

A constructor can use the super keyword to call the constructor of the super class.

You can create instance properties inside the constructor:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

Alternatively, if your instance properties’ values do not depend on the constructor’s arguments, you can define them as class fields.

“Class body” (MDN Web Docs). Retrieved November 11, 2024.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a static initialization block?

A

Static initialization blocks are declared within a class. It contains statements to be evaluated during class initialization. This permits more flexible initialization logic than static properties, such as using try...catch or setting multiple fields from a single value. Initialization is performed in the context of the current class declaration, with access to private state, which allows the class to share information of its private properties with other classes or functions declared in the same scope

Syntax

class ClassWithSIB {
  static {
    // …
  }
}

Without static initialization blocks, complex static initialization might be achieved by calling a static method after the class declaration:

class MyClass {
  static init() {
    // Access to private static fields is allowed here
  }
}

MyClass.init();

However, this approach exposes an implementation detail (the init() method) to the user of the class. On the other hand, any initialization logic declared outside the class does not have access to private static fields. Static initialization blocks allow arbitrary initialization logic to be declared within the class and executed during class evaluation.

A class can have any number of static {} initialization blocks in its class body. These are evaluated, along with any interleaved static field initializers, in the order they are declared. Any static initialization of a super class is performed first, before that of its sub classes.

The scope of the variables declared inside the static block is local to the block. This includes var, function, const, and let declarations. var declarations will not be hoisted out of the static block.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are static methods and fields?

A

The static keyword defines a static method or field for a class. Static properties (fields and methods) are defined on the class itself instead of each instance. Static methods are often used to create utility functions for an application, whereas static fields are useful for caches, fixed-configuration, or any other data that doesn’t need to be replicated across instances.

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  static displayName = "Point";
  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;

    return Math.hypot(dx, dy);
  }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
p1.displayName; // undefined
p1.distance; // undefined
p2.displayName; // undefined
p2.distance; // undefined

console.log(Point.displayName); // "Point"
console.log(Point.distance(p1, p2)); // 7.0710678118654755
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are class methods?

A

Methods are defined on the prototype of each class instance and are shared by all instances. Methods can be plain functions, async functions, generator functions, or async generator functions.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
  *getSides() {
    yield this.height;
    yield this.width;
    yield this.height;
    yield this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100
console.log([...square.getSides()]); // [10, 10, 10, 10]

They are not required but expected to use this inside the method body. Otherwise the method should become static or a helper function that lives outside the class definition.

“Class body” (MDN Web Docs). Retrieved November 18, 2024.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are public class field declarations?

A

Publick class fields are writable, enumerable, and configurable properties. As such, unlike their private counterparts, they participate in prototype inheritance.

Syntax

class ClassWithField {
  instanceField;
  instanceFieldWithInitializer = "instance field";
  static staticField;
  static staticFieldWithInitializer = "static field";
}

There are some additional syntax restrictions:

  • The name of a static property (field or method) cannot be prototype.
  • The name of a class field (static or instance) cannot be constructor.

Field initializers can refer to field values above it, but not below it. All instance and static methods are added beforehand and can be accessed, although calling them may not behave as expected if they refer to fields below the one being initialized.

class C {
  a = 1;
  b = this.c;
  c = this.a + 1;
  d = this.c + 1;
}

const instance = new C();
console.log(instance.d); // 3
console.log(instance.b); // undefined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are class private properties?

A

Private properties are counterparts of the regular class properties which are public, including class fields, class methods, etc. Private properties get created by using a hash # prefix and cannot be legally referenced outside of the class. The privacy encapsulation of these class properties is enforced by JavaScript itself. The only way to access a private property is via dot notation, and you can only do so within the class that defines the private property.

Private properties were not native to the language before this syntax existed. In prototypal inheritance, its behavior may be emulated with WeakMap objects or closures, but they can’t compare to the # syntax in terms of ergonomics.

Syntax

class ClassWithPrivate {
  #privateField;
  #privateFieldWithInitializer = 42;

  #privateMethod() {
    // …
  }

  static #privateStaticField;
  static #privateStaticFieldWithInitializer = 42;

  static #privateStaticMethod() {
    // …
  }
}

There are some additional syntax restrictions:

  • All private identifiers declared within a class must be unique. The namespace is shared between static and instance properties. The only exception is when the two declarations define a getter-setter pair.
  • The private identifier cannot be #constructor.
  • It is a syntax error to refer to # names from outside of the class. It is also a syntax error to refer to private properties that were not declared in the class body, or to attempt to remove declared properties with delete.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

List all the possible private properties of a class

A

Most class properties have their private counterparts:

  • Private fields
  • Private methods
  • Private static fields
  • Private static methods
  • Private getters
  • Private setters
  • Private static getters
  • Private static setters

These features are collectively called private properties. However, constructors cannot be private in JavaScript. To prevent classes from being constructed outside of the class, you have to use a private flag.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can you simulate a private constructor?

A

Many other languages include the capability to mark a constructor as private, which prevents the class from being instantiated outside of the class itself — you can only use static factory methods that create instances, or not be able to create instances at all. JavaScript does not have a native way to do this, but it can be accomplished by using a private static flag.

class PrivateConstructor {
  static #isInternalConstructing = false;

  constructor() {
    if (!PrivateConstructor.#isInternalConstructing) {
      throw new TypeError("PrivateConstructor is not constructable");
    }
    PrivateConstructor.#isInternalConstructing = false;
    // More initialization logic
  }

  static create() {
    PrivateConstructor.#isInternalConstructing = true;
    const instance = new PrivateConstructor();
    return instance;
  }
}

new PrivateConstructor(); // TypeError: PrivateConstructor is not constructable
PrivateConstructor.create(); // PrivateConstructor {}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How are class private properties declared?

A

Private properties are declared with # names (pronounced “hash names”), which are identifiers prefixed with #. The hash prefix is an inherent part of the property name — you can draw relationship with the old underscore prefix convention _privateField — but it’s not an ordinary string property, so you can’t dynamically access it with the bracket notation.

It is a syntax error to refer to # names from outside of the class. It is also a syntax error to refer to private properties that were not declared in the class body, or to attempt to remove declared properties with delete.

class ClassWithPrivateField {
  #privateField;

  constructor() {
    delete this.#privateField; // Syntax error
    this.#undeclaredField = 42; // Syntax error
  }
}

const instance = new ClassWithPrivateField();
instance.#privateField; // Syntax error

JavaScript, being a dynamic language, is able to perform this compile-time check because of the special hash identifier syntax, making it different from normal properties on the syntax level.

Note: Code run in the Chrome console can access private properties outside the class. This is a DevTools-only relaxation of the JavaScript syntax restriction.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly