JavaScript · Синтаксис · Начальный уровень
ООП: наследование и переопределение методов
Задачи по ООП в JavaScript на наследование, super(), constructor, переопределение методов, toString(), собственные методы классов и работу с объектами.
Краткое введение в тему и пояснения перед упражнениями (упражнения ниже):
toString() и пользовательские методы
#Паттерны наследования и методов
#Упражнения:
Animal и Dog через наследование.
#class Animal {
// ваш код здесь
}
class Dog extends Animal {
// ваш код здесь
}
Решение
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
toString() {
return `Dog: ${this.name}`;
}
}
Book со строковым представлением.
#class Book {
// ваш код здесь
}
Решение
class Book {
constructor(title, pages) {
this.title = title;
this.pages = pages;
}
length() {
return this.pages;
}
toString() {
return `Book: ${this.title} (${this.pages} pages)`;
}
}
User и Admin.
#class User {
// ваш код здесь
}
class Admin extends User {
// ваш код здесь
}
Решение
class User {
constructor(name) {
this.name = name;
}
toString() {
return this.name;
}
}
class Admin extends User {
toString() {
return `Admin: ${this.name}`;
}
}
Коробка с предметами.
#class Box {
// ваш код здесь
}
Решение
class Box {
constructor(itemsCount) {
this.itemsCount = itemsCount;
}
add(count) {
if (count > 0) {
this.itemsCount += count;
}
}
remove(count) {
if (count > 0) {
this.itemsCount -= count;
if (this.itemsCount < 0) {
this.itemsCount = 0;
}
}
}
getCount() {
return this.itemsCount;
}
}
Message со спам-флагом.
#class Message {
// ваш код здесь
}
Решение
class Message {
constructor(text) {
this.text = text;
this.spam = null;
this.spamTriggers = ["куплю", "дорого"];
}
isSpam() {
if (this.spam !== null) {
return this.spam;
}
for (let trigger of this.spamTriggers) {
if (this.text.toLowerCase().includes(trigger)) {
this.spam = true;
return true;
}
}
this.spam = false;
return false;
}
length() {
return this.text.length;
}
}
let m = new Message("Куплю старые телевизоры дорого!!!");
console.log(m.isSpam());
console.log(m.length());
Employee и Manager.
#class Employee {
// ваш код здесь
}
class Manager extends Employee {
// ваш код здесь
}
Решение
class Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
changeSalary(coef) {
this.salary = Math.round(this.salary * coef);
}
}
class Manager extends Employee {
toString() {
return `Manager ${this.name} earns ${this.salary}`;
}
}
let manager = new Manager("Bob", 1000);
manager.changeSalary(1.1);
console.log(manager.toString());
Playlist и CustomPlaylist.
#class Playlist {
// ваш код здесь
}
Решение
class Playlist {
constructor(songs) {
this.songs = songs;
}
add(song) {
if (!this.songs.includes(song)) {
this.songs.push(song);
}
}
remove(song) {
if (this.songs.includes(song)) {
this.songs.splice(this.songs.indexOf(song), 1);
}
}
reverse() {
this.songs.reverse();
}
length() {
return this.songs.length;
}
isEmpty() {
return this.songs.length === 0;
}
}
class CustomPlaylist extends Playlist {
add(song) {
this.songs.push(song);
}
}
Именованный CustomPlaylist.
#class CustomPlaylist extends Playlist {
constructor(songs, name) {
super(songs);
// ваш код здесь
}
add(song) {
this.songs.push(song);
}
}
Решение
class Playlist {
constructor(songs) {
this.songs = songs;
}
add(song) {
if (!this.songs.includes(song)) {
this.songs.push(song);
}
}
}
class CustomPlaylist extends Playlist {
constructor(songs, name) {
super(songs);
this.name = name;
}
add(song) {
this.songs.push(song);
}
toString() {
return `Playlist: ${this.name}`;
}
}
MagicBox со случайным предметом.
#class Box {
constructor() {
this.items = [];
this.itemsCount = this.items.length;
}
add(item) {
this.items.push(item);
this.itemsCount = this.items.length;
}
remove(item) {
if (this.items.includes ? this.items.includes(item) : (item in this.items)) {
this.items.splice(this.items.indexOf(item), 1);
this.itemsCount = this.items.length;
} else {
console.log("Кот из коробки говорит: Такого тут нет, до свидания!");
}
}
length() {
return this.itemsCount;
}
}
let things = ["Шапка", "Зонтик", "Кружка"];
class MagicBox extends Box {
constructor() {
// вызовите super() и добавьте случайный предмет
}
}
Решение
function choice(items) {
return items[Math.floor(Math.random() * items.length)];
}
class Box {
constructor() {
this.items = [];
this.itemsCount = this.items.length;
}
add(item) {
this.items.push(item);
this.itemsCount = this.items.length;
}
remove(item) {
if (this.items.includes(item)) {
this.items.splice(this.items.indexOf(item), 1);
this.itemsCount = this.items.length;
} else {
console.log("Кот из коробки говорит: Такого тут нет, до свидания!");
}
}
length() {
return this.itemsCount;
}
}
const things = ["Шапка", "Зонтик", "Кружка"];
class MagicBox extends Box {
constructor() {
super();
this.items.push(choice(things));
this.itemsCount = this.items.length;
}
}