4.1 Основы классов
Классы в TypeScript представляют собой шаблоны для создания объектов. Они могут содержать свойства и методы, которые описывают характеристики и поведение объектов.
Объявление класса
Для объявления класса в TypeScript используется ключевое слово class, за которым следует имя класса и тело класса в фигурных скобках {}.
Пример:
"use strict";
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let person = new Person('Alice', 30);
person.greet(); // Вывод: Hello, my name is Alice and I am 30 years old.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let person = new Person('Alice', 30);
person.greet(); // Вывод: Hello, my name is Alice and I am 30 years old.
Здесь класс Person имеет два свойства (name и age), конструктор для инициализации этих свойств и метод greet, который выводит приветственное сообщение.
Конструкторы
Конструктор — это специальный метод, который вызывается при создании нового экземпляра класса. В конструкторе обычно инициализируются свойства объекта.
Синтаксис конструктора
Конструктор объявляется с использованием ключевого слова constructor.
Пример:
"use strict";
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
displayInfo() {
console.log(`Car: ${this.make} ${this.model}, Year: ${this.year}`);
}
}
let myCar = new Car('Toyota', 'Camry', 2020);
myCar.displayInfo(); // Вывод: Car: Toyota Camry, Year: 2020
class Car {
make: string;
model: string;
year: number;
constructor(make: string, model: string, year: number) {
this.make = make;
this.model = model;
this.year = year;
}
displayInfo(): void {
console.log(`Car: ${this.make} ${this.model}, Year: ${this.year}`);
}
}
let myCar = new Car('Toyota', 'Camry', 2020);
myCar.displayInfo(); // Вывод: Car: Toyota Camry, Year: 2020
Здесь конструктор класса Car принимает три параметра (make, model, year) и инициализирует соответствующие свойства объекта.
Инкапсуляция
Инкапсуляция — это один из принципов ООП, который предполагает сокрытие внутреннего состояния объекта и предоставление методов для работы с этим состоянием. В TypeScript инкапсуляция достигается с помощью модификаторов доступа — public, private и protected.
Пример:
"use strict";
class BankAccount {
constructor(initialBalance) {
this.balance = initialBalance;
}
deposit(amount) {
this.balance += amount;
}
withdraw(amount) {
if (amount <= this.balance) {
this.balance -= amount;
}
else {
console.log('Insufficient funds');
}
}
getBalance() {
return this.balance;
}
}
let account = new BankAccount(1000);
account.deposit(500);
account.withdraw(300);
console.log(account.getBalance()); // Вывод: 1200
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
deposit(amount: number): void {
this.balance += amount;
}
withdraw(amount: number): void {
if (amount <= this.balance) {
this.balance -= amount;
} else {
console.log('Insufficient funds');
}
}
getBalance(): number {
return this.balance;
}
}
let account = new BankAccount(1000);
account.deposit(500);
account.withdraw(300);
console.log(account.getBalance()); // Вывод: 1200
Здесь свойство balance закрытое (private), и доступ к нему возможен только через методы deposit, withdraw и getBalance.
4.2 Методы класса
Методы класса определяют поведение объектов и могут выполнять различные действия, такие как манипуляция данными, выполнение расчетов и взаимодействие с другими объектами.
Пример:
"use strict";
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
calculateArea() {
return this.width * this.height;
}
calculatePerimeter() {
return 2 * (this.width + this.height);
}
}
let myRectangle = new Rectangle(10, 20);
console.log(`Area: ${myRectangle.calculateArea()}`); // Вывод: Area: 200
console.log(`Perimeter: ${myRectangle.calculatePerimeter()}`); // Вывод: Perimeter: 60
class Rectangle {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
calculateArea(): number {
return this.width * this.height;
}
calculatePerimeter(): number {
return 2 * (this.width + this.height);
}
}
let myRectangle = new Rectangle(10, 20);
console.log(`Area: ${myRectangle.calculateArea()}`); // Вывод: Area: 200
console.log(`Perimeter: ${myRectangle.calculatePerimeter()}`); // Вывод: Perimeter: 60
Здесь у класса Rectangle есть два метода: calculateArea для вычисления площади и calculatePerimeter для вычисления периметра прямоугольника.
Статические свойства и методы
Статические свойства и методы принадлежат самому классу, а не его экземплярам. Они объявляются с использованием ключевого слова static.
Пример:
"use strict";
class MathUtil {
static calculateCircumference(radius) {
return 2 * MathUtil.pi * radius;
}
}
MathUtil.pi = 3.14;
console.log(MathUtil.pi); // Вывод: 3.14
console.log(MathUtil.calculateCircumference(10)); // Вывод: 62.800000000000004
class MathUtil {
static pi: number = 3.14;
static calculateCircumference(radius: number): number {
return 2 * MathUtil.pi * radius;
}
}
console.log(MathUtil.pi); // Вывод: 3.14
console.log(MathUtil.calculateCircumference(10)); // Вывод: 62.800000000000004
Здесь pi и calculateCircumference статические, и их можно вызвать напрямую через класс MathUtil.
Getter и Setter
Геттеры и сеттеры позволяют контролировать доступ к свойствам объекта, обеспечивая инкапсуляцию и валидацию данных.
Пример:
"use strict";
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(newName) {
if (newName.length > 0) {
this._name = newName;
}
else {
console.log('Name cannot be empty');
}
}
}
let person = new Person('Alice');
console.log(person.name); // Вывод: Alice
person.name = 'Bob';
console.log(person.name); // Вывод: Bob
person.name = ''; // Вывод: Name cannot be empty
class Person {
private _name: string;
constructor(name: string) {
this._name = name;
}
get name(): string {
return this._name;
}
set name(newName: string) {
if (newName.length > 0) {
this._name = newName;
} else {
console.log('Name cannot be empty');
}
}
}
let person = new Person('Alice');
console.log(person.name); // Вывод: Alice
person.name = 'Bob';
console.log(person.name); // Вывод: Bob
person.name = ''; // Вывод: Name cannot be empty
В этом примере геттер name позволяет получить значение свойства _name, а сеттер name позволяет установить новое значение с проверкой на непустую строку.
4.3 Примеры
Давайте рассмотрим примеры использования классов в реальных проектах.
Классы широко используются в реальных проектах для моделирования различных сущностей и их взаимодействий.
Пример 1: Моделирование пользователя
"use strict";
class User {
constructor(id, name, email) {
this.id = id;
this.name = name;
this.email = email;
}
getDetails() {
return `User: ${this.name}, Email: ${this.email}`;
}
}
let user = new User(1, 'Alice', 'alice@example.com');
console.log(user.getDetails()); // Вывод: User: Alice, Email: alice@example.com
class User {
private id: number;
private name: string;
private email: string;
constructor(id: number, name: string, email: string) {
this.id = id;
this.name = name;
this.email = email;
}
getDetails(): string {
return `User: ${this.name}, Email: ${this.email}`;
}
}
let user = new User(1, 'Alice', 'alice@example.com');
console.log(user.getDetails()); // Вывод: User: Alice, Email: alice@example.com
Пример 2: Управление задачами
"use strict";
class Task {
constructor(id, title) {
this.id = id;
this.title = title;
this.completed = false;
}
complete() {
this.completed = true;
}
display() {
console.log(`Task: ${this.title}, Completed: ${this.completed}`);
}
}
let task = new Task(1, 'Learn TypeScript');
task.display(); // Вывод: Task: Learn TypeScript, Completed: false
task.complete();
task.display(); // Вывод: Task: Learn TypeScript, Completed: true
class Task {
id: number;
title: string;
completed: boolean;
constructor(id: number, title: string) {
this.id = id;
this.title = title;
this.completed = false;
}
complete(): void {
this.completed = true;
}
display(): void {
console.log(`Task: ${this.title}, Completed: ${this.completed}`);
}
}
let task = new Task(1, 'Learn TypeScript');
task.display(); // Вывод: Task: Learn TypeScript, Completed: false
task.complete();
task.display(); // Вывод: Task: Learn TypeScript, Completed: true
Пример 3: Управление продуктами
"use strict";
class Product {
constructor(id, name, price) {
this.id = id;
this.name = name;
this.price = price;
}
display() {
console.log(`Product: ${this.name}, Price: $${this.price}`);
}
}
let product = new Product(101, 'Laptop', 1200);
product.display(); // Вывод: Product: Laptop, Price: $1200
class Product {
id: number;
name: string;
price: number;
constructor(id: number, name: string, price: number) {
this.id = id;
this.name = name;
this.price = price;
}
display(): void {
console.log(`Product: ${this.name}, Price: $${this.price}`);
}
}
let product = new Product(101, 'Laptop', 1200);
product.display(); // Вывод: Product: Laptop, Price: $1200
ПЕРЕЙДИТЕ В ПОЛНУЮ ВЕРСИЮ