Skip to content

Классы

Создание объекта на основе класса

class Student {
fullName; // поле класса
age;
marks;
}
const std = new Student();
std.fullName = "John Doe";
std.age = 20;
std.marks = [90, 80, 70, 60, 50];
console.log(std);

Методы

class Student {
fullName; // свойство
age;
marks;
sayHello() {
console.log(`Hello`);
}
}
const std = new Student();
std.sayHello();

this

class Student {
fullName; // свойство
age;
marks;
sayHello() {
console.log(`Hello ${this.fullName}`);
}
marksAverage() {
const sum = this.marks.reduce((acc, cur) => acc + cur, 0);
return sum / this.marks.length;
}
showThis() {
console.log(this);
}
}
const std = new Student();
std.fullName = "Alex Smith";
std.age = 20;
std.marks = [10, 20, 30, 40, 50];
std.sayHello();
console.log(std.marksAverage());
std.showThis();

Конструктор

class Student {
fullName; // свойство
age;
marks;
constructor(fullName, age, marks) {
this.fullName = fullName;
this.age = age;
this.marks = marks;
}
}
const std = new Student("John", 20, 90);
console.log(std);

Сокращенная запись

class Student {
constructor(fullName, age, marks) {
this.fullName = fullName;
this.age = age;
this.marks = marks;
}
}
const std = new Student("John", 20, 90);
console.log(std);

Наследование

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const prs = new Person("John", 30);
console.log(prs);
prs.sayHello();
class Student extends Person {
constructor(name, age, school) {
super(name, age);
this.school = school;
}
// sayHello() {
// console.log(`Hello, my name is ${this.name} and I am ${this.age} years old. I am from ${this.school}.`);
// }
}
const std = new Student("John", 30, "MIT");
console.log(std);
std.sayHello();