- Published on
Day23 : Learning TypeScript: ES6 Class
- Authors

- Name
- irisjustdoit
- @irisjustdoit
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
- constructor: Used to initialize an object of a class. A class can only have one constructor.
- extends: Use
extendsto inherit a class, creating a subclass that can use the properties and methods of the parent class. - super: You can use
superto access the parent class's properties and methods. Thesuperkeyword must be used beforethis. - prototype methods: Methods defined in the class.
- getter: Use the
getkeyword to change how a property is read. - setter: Use the
setkeyword to change how a property is assigned. - static method: Use the
statickeyword 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()andsetVal('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
thisand the other without. If usingthis, it must be called withcall. 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,
CatandDogboth inherit fromAnimal, but implement their owneatmethods. In this case, we do not need to know whether it is aCator aDogfor a specific instance; we can directly call theeatmethod, and the program will automatically determine how to executeeat. - Modifiers: Keywords used to limit the nature of members or types. For example,
publicindicates 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
