Class & Instances
Classes are blueprints for objects. Objects are instances of classes. A class defines what an object looks like and what properties and methods it contains. Classes make it easy to create multiple similar objects.
Classes are syntactic sugar for constructors.
In TypeScript, class is also a type, just like basic data types (such as
string
andnumber
) and other custom types. Therefore, we can combine multiple classes into a union type.- Class: defines the abstract characteristics of a thing, including its properties and methods
- Object: instance of a class, generated through
new
- Three major characteristics of object-oriented (OOP): encapsulation, inheritance, and polymorphism
- Encapsulation: Hide the details of data operation and expose only the external interface. The external caller does not need (and cannot) know the details to access the object through the externally provided interface. This also ensures that the outside world cannot arbitrarily change the data inside the object.
- Inheritance: A subclass inherits a parent class. In addition to having all the characteristics of the parent class, the subclass also has some more specific characteristics.
- Polymorphism: Different related classes generated by inheritance can have different responses to the same method. For example,
Cat
andDog
both inherit fromAnimal
, but implement their owneat
method respectively. At this time, for a certain instance, we can directly call theeat
method without knowing whether it isCat
orDog
, and the program will automatically determine how to executeeat
-Accessors (getters & setters): used to change the reading and assignment behavior of attributes - Modifiers: Modifiers are keywords used to qualify the properties of members or types. For example,
public
means public properties or methods - Abstract Class: An abstract class is a base class for other classes to inherit from. Abstract classes are not allowed to be instantiated. Abstract methods in abstract classes must be implemented in subclasses
- Interfaces: Public properties or methods between different classes, which can be abstracted into an interface. Interfaces can be implemented by classes. A class can only inherit from another class, but can implement multiple interfaces
Class writing
Capitalize the first letter of class names.
Constructor method: constructor is the keyword. It is essentially a function that is bound to the class, and to any objects created based on the class, and is executed when the class creates an object. It is used to do some initialization work for the constructed object. Constructors use this to store parameters into class properties.
1
2
3
4
5
6
7class Department {
name: string; //You can assign an initial value here with name: string = "default";, but generally you don't do this, instead use a constructor.
constructor(n: string) {
this.name = n; //Store the parameters in the attribute name.
}
}Create an instance of a class: Use the keyword
new
and pass in the parameters required in the constructor.1
const accounting = new Department("Accounting");
The difference between classes in TS and JS
ES6 version of JS
In TS, the type of the attribute is first declared, and then the constructor is used to pass in the parameters and assign values to the attribute. In JS, there is no need to declare attribute types, so attributes are not declared in advance.
1
2
3
4
5
6
7//Compiled JS code
class Department { //There is no name: string; line
constructor(n: string) {
this.name = n;
}
}
const accounting = new Department("Accounting");
ES5 version of JS
There are no classes in ES5 JS. So it became a constructor.
1
2
3
4
5
6
7
8
var Department = (function () {
function Department(n) {
this.name = n;
}
return Department;
})
var accounting = new Department("Accounting");
this in TS
To reference a property or method of a class from within the class, the this keyword must be used.
TS can change the default point of this by declaring this pointer to the method in the class, such as
describe(this: Department){}
.In JS, this points to the object in which the function is called. Functions must be called by objects. For example:
1
2
3
4
5
6
7
8
9
10
11
12class Department {
name: string;
constructor(n: string) {
this.name = n;
}
describe(){
console.log("Department: " + this.name);
}
}
const accounting = new Department("Accounting");
const accountingCopy = { describe: accounting.describe };
accountingCopy.describe(); //The output is Department: undefind. Because this points to accountingCopy.In TS, this in the method
describe(this: Department){}
will always point to the instance of Department.1
2
3
4
5
6
7
8
9
10
11
12class Department {
name: string;
constructor(n: string) {
this.name = n;
}
describe(this: Department){ //Let this point to the instance of department
console.log("Department: " + this.name);
}
}
const accounting = new Department("Accounting");
const accountingCopy = { describe: accounting.describe };
accountingCopy.describe(); //An error will be reported here. Because this in the describe() method cannot find the name attribute of accountingCopyIf you add the
name
attribute to theaccountingCopy
object, the code will run normally.1
2const accountingCopy = { name: "DUMMY", describe: accounting.describe };
accountingCopy.describe(); //The output is Department: DUMMY.
private and public modifiers
The properties and methods in the class are accessible from the outside by default (that is, public by default).
For example, there is an array in the class, and there are methods in the class to modify the array:
1
2
3
4
5
6class Department {
employees: string[] = [];
addEmployee(employee: string) {
this.employees.push(employee);
}
}At this time, if we create an instance and write
accounting.employees[2] = "Anna"
, theemployees
attribute in the instance can also be modified. But this is not standardized and can easily lead to errors. What we want is that the array can only be modified externally by calling theaddEmployee()
method in the class.Therefore, you need to use the
private
attribute at this time. At this time the employees property can only be accessed from within the class.1
2
3
4
5
6class Department {
private employees: string[] = [];
addEmployee(employee: string) {
this.employees.push(employee);
}
}Note that methods in a class can also be marked private.
1
2
3
4
5
6
7
8
9
10
11
12
13
14class Example {
private doSomethingPrivate() {
console.log('This is a private method.');
}
public doSomethingPublic() {
console.log('This is a public method.');
this.doSomethingPrivate(); // Private methods can be called in public methods
}
}
const example = new Example();
example.doSomethingPublic(); // Public methods can be called
example.doSomethingPrivate(); // Private methods cannot be called
Abbreviation for class instance initialization
In the above code, to initialize a property we need to specify the type of the property in the class, and then use this in the constructor to pass the parameters into the initial value:
1
2
3
4
5
6
7
8class Department {
private name: string;
id: string;
constructor(n: string, i: string) {
this.name = n;
this.id = i;
}
}Writing this way is cumbersome. You can remove the assignment in the constructor and the attribute declaration in the class, and complete all operations in the constructor parameter at once. At this time, the parameters will still be passed in, and the value will be stored in the created attribute after being passed in. Simplified to:
1
2
3class Department {
constructor(private name: string, public id: string) {}
}It should be noted here that public cannot be omitted at this time. **Because this is an explicit TS directive, it tells TS that you not only want these parameters in the constructor, but also create properties for this class with the exact same names.
readonly modifier
Used to identify certain fields that cannot be changed after initialization. For example:
1
2
3class Department {
constructor(private name: string, public readonly id: string) {}
}readonly
can also be used in interfaces. Use thereadonly
keyword in the interface to mark a property as a read-only property. The value of this property can only be set when the object is initialized or in the constructor, and cannot be modified again after the object is created.