Happylab Logo
Published on

Day23 : Learning TypeScript: ES6 Class

Authors

Day23 : Learning TypeScript: ES6 Class

Since I don't use Classes much, this article will note the usage of ES6 Classes. The next article will delve into using classes in TypeScript and implementing interfaces with classes. Let's first understand ES6 Classes!

If there are any mistakes, please feel free to leave comments. Thank you!

What is a Class?

In simple terms, a class is a template for objects, defining the abstract characteristics of something, including its properties and methods, providing a more concise syntax for creating objects and handling inheritance.


How to Define a Class?

There are two ways to define a class: class declaration and class expressions (similar to defining functions).

1. Class Declaration

You use the keyword class, along with a name (like "Point"), which is usually capitalized.

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

2. Class Expressions

Class expressions also require the class keyword, but it can have a name or be unnamed.

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

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

Some Things to Know About Classes

  1. constructor: Used to initialize an object of a class. A class can only have one constructor.
  2. extends: Use extends to inherit a class, creating a subclass that can use the properties and methods of the parent class.
  3. super: You can use super to access the parent class's properties and methods. The super keyword must be used before this.
  4. prototype methods: Methods defined in the class.
  5. getter: Use the get keyword to change how a property is read.
  6. setter: Use the set keyword to change how a property is assigned.
  7. static method: Use the static keyword to create static methods in a class, which cannot be accessed by other methods in the class. Static methods are often used to create utility functions for applications.

Here's an example for better understanding:

class Point {
  constructor(x = 0, y = 0) { // default to 0
    this.x = x;
    this.y = y;
  }

  printPoint() {
    console.log(`x: ${this.x}, y: ${this.y}`);
  }

  get xValue() {
    return this.x;
  }

  set xValue(z) {
    if (z < 0) {
      z = 0;
    }
    this.x = z;
  }

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

    return Math.sqrt(dx * dx + dy * dy);
  }
}

// Use new to create an instance
let p = new Point(2, 4);
p.printPoint(); // x: 2, y: 4

// Access getter like a property
console.log(`get x value: ${p.xValue}`); // get x value: 2

// Assign value using setter
p.xValue = -5;
console.log(`set x value: ${p.xValue}`); // set x value: 0

// Static method
let p1 = new Point(10, 12);
let p2 = new Point(16, 18);
console.log(Point.distance(p1, p2)); // 8.48528137423857
class AddPoint extends Point {
  constructor(x, y) {
    super(x, y); // Call the parent class's constructor
    this.x = x;
    this.y = y;
  }

  add() {
    this.printPoint(); // Inherited method
    return `total = ${this.x + this.y}`;
  }
}

let p3 = new AddPoint(5, 7);
console.log(p3.add()); // total = 12

Notes:

  • You can omit the constructor; if not specified, the default constructor will be used, which looks like constructor() {}.
  • The benefit of getters and setters is that they do not change the original constructor's properties and can be used like class properties.
  • Initially, I thought using getters and setters was convenient, as they can be used like properties without creating methods. However, I read an article suggesting not to use them due to potential unexpected side effects and difficulty in testing and maintenance. If needed, use prototype methods to create your own, such as getVal() and setVal('Hello'). The Airbnb JS Style Guide mentions this. Since I have not used getters and setters, I want to know what side effects they might have.
  • Static methods can be used in two ways: one with this and the other without. If using this, it must be called with call. Refer to this article.
  • Object: An instance of a class created using new.
  • The three main characteristics of Object-Oriented Programming (OOP): Encapsulation, Inheritance, and Polymorphism.
  • Encapsulation: Hiding the details of data manipulation and exposing only the interface to the outside. The external caller does not need (and cannot) know the details and can access the object through the provided interface, ensuring that the external world cannot arbitrarily change the internal data of the object.
  • Inheritance: A subclass inherits from a parent class, and the subclass has all the features of the parent class, along with some more specific features.
  • Polymorphism: Related different classes generated from inheritance can respond differently to the same method. For example, Cat and Dog both inherit from Animal, but implement their own eat methods. In this case, we do not need to know whether it is a Cat or a Dog for a specific instance; we can directly call the eat method, and the program will automatically determine how to execute eat.
  • Modifiers: Keywords used to limit the nature of members or types. For example, public indicates a public property or method.
  • Abstract Class: An abstract class serves as a base class for other classes and cannot be instantiated. Abstract methods in an abstract class must be implemented in subclasses.
  • Interfaces: Common properties or methods between different classes can be abstracted into an interface. An interface can be implemented by a class. A class can only inherit from one class but can implement multiple interfaces.

Yay! Happy Double Ten Day! Thank you for reading! Tomorrow we will delve into using classes in TypeScript. See you tomorrow!


References

https://willh.gitbook.io/typescript-tutorial/advanced/class https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Classes https://pjchender.dev/javascript/js-class/ https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Classes/static