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 зі spam-прапорцем.
#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;
}
}