Kurs JavaScript i TypeScript · Moduł 2: Funkcje, tablice i obiekty
Tworzenie obiektów (literały, konstruktory)
W tej lekcji8
W Parku Jurajskim używamy obiektów JavaScript do reprezentowania wielu elementów naszego ekosystemu - od dinozaurów i ich zachowań, przez obszary parku, po dane pracowników i procedury bezpieczeństwa. Obiekty są fundamentalnym typem danych w JavaScript, umożliwiającym tworzenie złożonych struktur danych z właściwościami i metodami.
Literały obiektów
Najprostszym sposobem tworzenia obiektów w JavaScript jest użycie literału obiektu - notacji z nawiasami klamrowymi {}.
// Prosty obiekt dinozaura utworzony za pomocą literału obiektu
const velociraptor = {
name: "Blue",
species: "Velociraptor",
age: 4,
length: 2.1, // metry
weight: 80, // kilogramy
maxSpeed: 64, // km/h
diet: "carnivore",
location: "Sektor B",
dangerous: true
};
console.log(velociraptor.name); // "Blue"
console.log(velociraptor.species); // "Velociraptor"
console.log(velociraptor.maxSpeed); // 64Dostęp do właściwości
Możemy uzyskać dostęp do właściwości obiektu na dwa sposoby:
// Notacja kropkowa
console.log(velociraptor.diet); // "carnivore"
// Notacja nawiasowa (przydatna, gdy nazwa właściwości jest przechowywana w zmiennej)
const propertyName = "location";
console.log(velociraptor[propertyName]); // "Sektor B"
// Notacja nawiasowa jest też przydatna, gdy nazwa właściwości zawiera znaki specjalne lub spacje
const dinoDetails = {
"full name": "Velociraptor antirrhopus",
"security-level": "Alpha"
};
console.log(dinoDetails["full name"]); // "Velociraptor antirrhopus"
console.log(dinoDetails["security-level"]); // "Alpha"Metody obiektów
Obiekty mogą zawierać również funkcje, które nazywamy metodami:
const velociraptor = {
name: "Blue",
species: "Velociraptor",
age: 4,
hunger: 50, // procent (0-100)
health: 100, // procent (0-100)
// Metoda do karmienia dinozaura
feed: function() {
if (this.hunger <= 0) {
return "Blue nie jest głodna.";
}
this.hunger -= 30;
if (this.hunger < 0) this.hunger = 0;
return "Blue została nakarmiona. Poziom głodu: " + this.hunger + "%";
},
// Krótsza składnia metody (wprowadzona w ES6)
makeSound() {
return "Blue wydaje ostry, przenikliwy dźwięk!";
},
// Metoda sprawdzająca stan zdrowia
checkStatus() {
return `Dinozaur: ${this.name} (Gatunek: ${this.species})
Status zdrowia: ${this.health}%
Poziom głodu: ${this.hunger}%
Stan ogólny: ${this.health > 80 ? "Doskonały" : this.health > 50 ? "Dobry" : "Wymaga opieki weterynaryjnej"}`;
}
};
console.log(velociraptor.makeSound()); // "Blue wydaje ostry, przenikliwy dźwięk!"
console.log(velociraptor.feed()); // "Blue została nakarmiona. Poziom głodu: 20%"
console.log(velociraptor.checkStatus());Słowo kluczowe this w metodach odnosi się do obiektu, na którym metoda jest wywoływana.
Dynamiczne dodawanie i usuwanie właściwości
Możemy dynamicznie dodawać i usuwać właściwości obiektów JavaScript:
const triceratops = {
name: "Trixie",
species: "Triceratops",
age: 6
};
// Dodawanie nowych właściwości
triceratops.health = 95;
triceratops["location"] = "Sektor C";
// Dodawanie metody
triceratops.updateHealth = function(amount) {
this.health += amount;
if (this.health > 100) this.health = 100;
if (this.health < 0) this.health = 0;
return `Zdrowie ${this.name} zaktualizowane do ${this.health}%`;
};
console.log(triceratops.updateHealth(-15)); // "Zdrowie Trixie zaktualizowane do 80%"
// Usuwanie właściwości
delete triceratops.age;
console.log(triceratops.age); // undefinedKonstruktory i operator new
Gdy potrzebujemy stworzyć wiele podobnych obiektów, efektywniejszym podejściem jest użycie funkcji konstruktora i operatora new.
// Funkcja konstruktora dla dinozaurów
function Dinosaur(name, species, age, diet) {
this.name = name;
this.species = species;
this.age = age;
this.diet = diet;
this.health = 100;
this.hunger = 50;
// Metoda wspólna dla wszystkich dinozaurów
this.feed = function() {
this.hunger -= 30;
if (this.hunger < 0) this.hunger = 0;
return `${this.name} został(a) nakarmiony(a). Poziom głodu: ${this.hunger}%`;
};
}
// Tworzenie nowych instancji dinozaurów
const blue = new Dinosaur("Blue", "Velociraptor", 4, "carnivore");
const trixie = new Dinosaur("Trixie", "Triceratops", 6, "herbivore");
const rex = new Dinosaur("Rex", "Tyrannosaurus", 8, "carnivore");
console.log(blue.species); // "Velociraptor"
console.log(trixie.diet); // "herbivore"
console.log(rex.feed()); // "Rex został(a) nakarmiony(a). Poziom głodu: 20%"Funkcja konstruktora tworzy "szablon" dla obiektów, a operator new tworzy nową instancję obiektu zgodnie z tym szablonem.
Zalety konstruktorów:
- Spójność - wszystkie obiekty mają ten sam zestaw właściwości i metod
- Skalowalność - łatwiej tworzyć wiele podobnych obiektów
- Czytelność - kod staje się bardziej przewidywalny i łatwy do utrzymania
Sprawdzanie typu obiektu - operator instanceof
Możemy sprawdzić, czy obiekt został utworzony za pomocą konkretnego konstruktora:
console.log(blue instanceof Dinosaur); // true
console.log(velociraptor instanceof Dinosaur); // false (został utworzony jako literał)Klasy (ES6+)
W nowszych wersjach JavaScript (ES6+) wprowadzono klasy, które zapewniają bardziej przyjazną składnię dla programowania obiektowego. Pod maską nadal są to funkcje konstruktora, ale z bardziej czytelną składnią.
class Dinosaur {
constructor(name, species, age, diet) {
this.name = name;
this.species = species;
this.age = age;
this.diet = diet;
this.health = 100;
this.hunger = 50;
this.isAsleep = false;
}
// Metody są automatycznie dodawane do prototypu
feed() {
if (this.isAsleep) {
return `${this.name} śpi. Lepiej go/jej nie budzić podczas karmienia.`;
}
this.hunger -= 30;
if (this.hunger < 0) this.hunger = 0;
return `${this.name} został(a) nakarmiony(a). Poziom głodu: ${this.hunger}%`;
}
sleep() {
this.isAsleep = true;
return `${this.name} zasypia.`;
}
wakeUp() {
this.isAsleep = false;
return `${this.name} budzi się.`;
}
getStatus() {
return `
Dinozaur: ${this.name} (Gatunek: ${this.species})
Wiek: ${this.age} lat
Dieta: ${this.diet === "carnivore" ? "Mięsożerna" : "Roślinożerna"}
Status zdrowia: ${this.health}%
Poziom głodu: ${this.hunger}%
Stan: ${this.isAsleep ? "Śpi" : "Aktywny"}`;
}
}
// Tworzenie instancji klasy
const blue = new Dinosaur("Blue", "Velociraptor", 4, "carnivore");
console.log(blue.getStatus());
console.log(blue.sleep()); // "Blue zasypia."
console.log(blue.feed()); // "Blue śpi. Lepiej go/jej nie budzić podczas karmienia."
console.log(blue.wakeUp()); // "Blue budzi się."
console.log(blue.feed()); // "Blue został(a) nakarmiony(a). Poziom głodu: 20%"Dziedziczenie za pomocą klas
Klasy umożliwiają łatwe implementowanie dziedziczenia:
// Klasa bazowa
class Animal {
constructor(name, species) {
this.name = name;
this.species = species;
this.alive = true;
}
makeSound() {
return "Zwierzę wydaje dźwięk";
}
}
// Klasa pochodna dziedzicząca z Animal
class Dinosaur extends Animal {
constructor(name, species, diet) {
// Wywołujemy konstruktor klasy bazowej
super(name, species);
this.diet = diet;
this.health = 100;
}
// Nadpisujemy metodę z klasy bazowej
makeSound() {
if (this.diet === "carnivore") {
return "ROAR!!! Przerażający ryk!";
} else {
return "Łagodny, niski pomruk.";
}
}
// Dodajemy nowe metody
eat(food) {
if (this.diet === "carnivore" && food.type === "meat") {
return `${this.name} zjada ${food.name} z apetytem!`;
} else if (this.diet === "herbivore" && food.type === "plant") {
return `${this.name} skubie ${food.name} zadowolony.`;
} else {
return `${this.name} nie jest zainteresowany jedzeniem ${food.name}.`;
}
}
}
// Obiekty reprezentujące jedzenie
const meat = { name: "mięso", type: "meat" };
const plants = { name: "rośliny", type: "plant" };
// Tworzymy instancje dinozaurów
const rex = new Dinosaur("Rex", "Tyrannosaurus", "carnivore");
const spike = new Dinosaur("Spike", "Stegosaurus", "herbivore");
console.log(rex.makeSound()); // "ROAR!!! Przerażający ryk!"
console.log(spike.makeSound()); // "Łagodny, niski pomruk."
console.log(rex.eat(meat)); // "Rex zjada mięso z apetytem!"
console.log(rex.eat(plants)); // "Rex nie jest zainteresowany jedzeniem rośliny."
console.log(spike.eat(plants)); // "Spike skubie rośliny zadowolony."Metody statyczne
Metody statyczne są wywoływane na samej klasie, a nie na jej instancjach:
class DinosaurDatabase {
static dinoCount = 0;
constructor(name, species) {
this.name = name;
this.species = species;
DinosaurDatabase.dinoCount++;
}
// Metoda instancji - wymaga utworzenia obiektu
getInfo() {
return `${this.name} (${this.species})`;
}
// Metoda statyczna - wywoływana na klasie, nie na instancji
static getTotalDinosaurCount() {
return `Całkowita liczba dinozaurów w bazie: ${DinosaurDatabase.dinoCount}`;
}
static compareAge(dino1, dino2) {
if (!dino1.age || !dino2.age) return "Brak danych o wieku.";
if (dino1.age > dino2.age) {
return `${dino1.name} jest starszy od ${dino2.name}.`;
} else if (dino1.age < dino2.age) {
return `${dino1.name} jest młodszy od ${dino2.name}.`;
} else {
return `${dino1.name} i ${dino2.name} są w tym samym wieku.`;
}
}
}
const dino1 = new DinosaurDatabase("Rex", "Tyrannosaurus");
dino1.age = 8;
const dino2 = new DinosaurDatabase("Blue", "Velociraptor");
dino2.age = 4;
const dino3 = new DinosaurDatabase("Trixie", "Triceratops");
dino3.age = 6;
console.log(DinosaurDatabase.getTotalDinosaurCount()); // "Całkowita liczba dinozaurów w bazie: 3"
console.log(DinosaurDatabase.compareAge(dino1, dino2)); // "Rex jest starszy od Blue."
console.log(DinosaurDatabase.compareAge(dino2, dino3)); // "Blue jest młodszy od Trixie."Object.create()
Metoda Object.create() pozwala na tworzenie nowych obiektów z określonym prototypem:
// Obiekt prototypowy dla wszystkich dinozaurów
const dinoPrototype = {
makeSound() {
return "Ryk!";
},
eat() {
return `${this.name} je.`;
}
};
// Tworzenie obiektu z prototypem dinoPrototype
const rex = Object.create(dinoPrototype);
rex.name = "Rex";
rex.species = "Tyrannosaurus";
console.log(rex.name); // "Rex"
console.log(rex.makeSound()); // "Ryk!"
console.log(rex.eat()); // "Rex je."Factory Functions (Funkcje fabryczne)
Funkcje fabryczne to funkcje, które tworzą i zwracają obiekty bez użycia new:
// Funkcja fabryczna do tworzenia obiektów dinozaurów
function createDinosaur(name, species, diet) {
return {
name, // Skrócona składnia dla name: name w ES6+
species,
diet,
health: 100,
hunger: 50,
feed() {
this.hunger -= 30;
if (this.hunger < 0) this.hunger = 0;
return `${this.name} został(a) nakarmiony(a). Poziom głodu: ${this.hunger}%`;
},
getStatus() {
return `${this.name} (${this.species}) - Zdrowie: ${this.health}%, Głód: ${this.hunger}%`;
}
};
}
const blue = createDinosaur("Blue", "Velociraptor", "carnivore");
const trixie = createDinosaur("Trixie", "Triceratops", "herbivore");
console.log(blue.getStatus()); // "Blue (Velociraptor) - Zdrowie: 100%, Głód: 50%"
console.log(blue.feed()); // "Blue został(a) nakarmiony(a). Poziom głodu: 20%"Praktyczne zastosowanie obiektów w Parku Jurajskim
System zarządzania dinozaurami
class DinosaurManager {
constructor() {
this.dinosaurs = [];
this.enclosures = [];
}
addDinosaur(dino) {
this.dinosaurs.push(dino);
console.log(`Dodano nowego dinozaura: ${dino.name} (${dino.species})`);
}
addEnclosure(enclosure) {
this.enclosures.push(enclosure);
console.log(`Dodano nowy wybieg: ${enclosure.name} (Pojemność: ${enclosure.capacity})`);
}
assignDinosaurToEnclosure(dinoName, enclosureName) {
const dino = this.dinosaurs.find(d => d.name === dinoName);
const enclosure = this.enclosures.find(e => e.name === enclosureName);
if (!dino) {
return `Błąd: Dinozaur o nazwie ${dinoName} nie znaleziony.`;
}
if (!enclosure) {
return `Błąd: Wybieg o nazwie ${enclosureName} nie znaleziony.`;
}
if (enclosure.dinosaurs.length >= enclosure.capacity) {
return `Błąd: Wybieg ${enclosureName} osiągnął maksymalną pojemność.`;
}
// Sprawdzenie czy drapieżniki nie są mieszane z roślinożercami
if (enclosure.dinosaurs.length > 0) {
const existingDiet = enclosure.dinosaurs[0].diet;
if (dino.diet === "carnivore" && existingDiet === "herbivore") {
return "Błąd: Nie można umieszczać drapieżników z roślinożercami!";
}
if (dino.diet === "herbivore" && existingDiet === "carnivore") {
return "Błąd: Nie można umieszczać roślinożerców z drapieżnikami!";
}
}
// Usunięcie dinozaura z poprzedniego wybiegu, jeśli był przypisany
this.enclosures.forEach(e => {
const index = e.dinosaurs.findIndex(d => d.name === dinoName);
if (index !== -1) {
e.dinosaurs.splice(index, 1);
}
});
// Przypisanie dinozaura do nowego wybiegu
enclosure.dinosaurs.push(dino);
dino.enclosure = enclosureName;
return `${dinoName} został(a) przypisany(a) do wybiegu ${enclosureName}.`;
}
getEnclosureReport(enclosureName) {
const enclosure = this.enclosures.find(e => e.name === enclosureName);
if (!enclosure) {
return `Błąd: Wybieg o nazwie ${enclosureName} nie znaleziony.`;
}
let report = `=== RAPORT DLA WYBIEGU: ${enclosure.name} ===
Pojemność: ${enclosure.dinosaurs.length}/${enclosure.capacity}
Status: ${enclosure.status}
Dinozaury:\n`;
if (enclosure.dinosaurs.length === 0) {
report += "Brak dinozaurów w tym wybiegu.";
} else {
enclosure.dinosaurs.forEach(dino => {
report += `- ${dino.name} (${dino.species}): Zdrowie: ${dino.health}%, Głód: ${dino.hunger}%\n`;
});
}
return report;
}
}
// Klasa dla dinozaurów
class Dinosaur {
constructor(name, species, diet) {
this.name = name;
this.species = species;
this.diet = diet;
this.health = 100;
this.hunger = 50;
this.enclosure = null; // Nazwa wybiegu, do którego przypisany jest dinozaur
}
}
// Klasa dla wybiegów
class Enclosure {
constructor(name, capacity, security) {
this.name = name;
this.capacity = capacity;
this.security = security; // poziom zabezpieczeń
this.status = "Operational";
this.dinosaurs = []; // Lista dinozaurów w wybiegu
}
}
// Użycie systemu zarządzania
const parkManager = new DinosaurManager();
// Tworzenie wybiegów
const carnivoreEnclosure = new Enclosure("Paddock A", 3, "Maximum");
const herbivoreEnclosure = new Enclosure("Paddock B", 5, "Standard");
parkManager.addEnclosure(carnivoreEnclosure);
parkManager.addEnclosure(herbivoreEnclosure);
// Tworzenie dinozaurów
const rex = new Dinosaur("Rex", "Tyrannosaurus", "carnivore");
const blue = new Dinosaur("Blue", "Velociraptor", "carnivore");
const trixie = new Dinosaur("Trixie", "Triceratops", "herbivore");
const spike = new Dinosaur("Spike", "Stegosaurus", "herbivore");
parkManager.addDinosaur(rex);
parkManager.addDinosaur(blue);
parkManager.addDinosaur(trixie);
parkManager.addDinosaur(spike);
// Przypisywanie dinozaurów do wybiegów
console.log(parkManager.assignDinosaurToEnclosure("Rex", "Paddock A"));
console.log(parkManager.assignDinosaurToEnclosure("Blue", "Paddock A"));
console.log(parkManager.assignDinosaurToEnclosure("Trixie", "Paddock B"));
console.log(parkManager.assignDinosaurToEnclosure("Spike", "Paddock B"));
// Próba przypisania roślinożercy do wybiegu drapieżników
console.log(parkManager.assignDinosaurToEnclosure("Trixie", "Paddock A"));
// Wyświetlanie raportów
console.log(parkManager.getEnclosureReport("Paddock A"));
console.log(parkManager.getEnclosureReport("Paddock B"));Podsumowanie
Obiekty są fundamentalnym elementem języka JavaScript i pozwalają nam modelować złożone struktury danych i zachowania. W Parku Jurajskim używamy ich do reprezentowania wszystkiego - od dinozaurów po system zarządzania całym parkiem.
Mamy kilka sposobów tworzenia obiektów:
- Literały obiektów - najprostszy sposób, idealny dla pojedynczych, unikalnych obiektów
- Funkcje konstruktora - gdy potrzebujemy tworzyć wiele podobnych obiektów
- Klasy (ES6+) - nowoczesna, czytelna składnia do tworzenia szablonów obiektów z dziedziczeniem
- Object.create() - tworzenie obiektów z określonym prototypem
- Funkcje fabryczne - funkcje zwracające nowe obiekty, alternatywa dla konstruktorów
Wybór konkretnej techniki zależy od sytuacji i potrzeb projektu. W złożonych aplikacjach, jak nasz system zarządzania Parkiem Jurajskim, najczęściej używamy kombinacji tych technik.
Kod do tej lekcji: index.js
// Obiekty - tworzenie - Park Jurajski
console.log("Laboratorium Obiektów JavaScript");
console.log("Tworzenie i konstruowanie obiektów\n");
// ===========================================
// 1. LITERAŁY OBIEKTOWE (najprostszy sposób)
// ===========================================
console.log("=== 1. Literały obiektowe ===");
// Podstawowy obiekt
const dinosaur1 = {
name: "T-Rex",
species: "Tyrannosaurus Rex",
age: 8,
weight: 8000,
carnivore: true
};
console.log("Dinozaur 1:");
console.log(` Imię: ${dinosaur1.name}`);
console.log(` Gatunek: ${dinosaur1.species}`);
console.log(` Wiek: ${dinosaur1.age} lat`);
// Obiekt z metodami
const dinosaur2 = {
name: "Blue",
species: "Velociraptor",
speed: 40,
// Metoda tradycyjna
roar: function() {
return `${this.name} ryczy: SHREEK!`;
},
// Metoda skrócona (ES6)
run() {
return `${this.name} biegnie z prędkością ${this.speed} km/h`;
}
};
console.log("\nDinozaur 2:");
console.log(` ${dinosaur2.roar()}`);
console.log(` ${dinosaur2.run()}`);
// ===========================================
// 2. KONSTRUKTORY FUNKCYJNE
// ===========================================
console.log("\n=== 2. Konstruktory funkcyjne ===");
function Dinosaur(name, species, age, weight, carnivore) {
this.name = name;
this.species = species;
this.age = age;
this.weight = weight;
this.carnivore = carnivore;
this.getInfo = function() {
return `${this.name} (${this.species}) - ${this.age} lat, ${this.weight}kg`;
};
this.roar = function() {
return `${this.name} says: ROAARRR!`;
};
}
const trex = new Dinosaur("Rexy", "T-Rex", 8, 8000, true);
const trike = new Dinosaur("Trike", "Triceratops", 7, 9000, false);
console.log("\nUtworzono przez konstruktor:");
console.log(` ${trex.getInfo()}`);
console.log(` ${trex.roar()}`);
console.log(` ${trike.getInfo()}`);
// ===========================================
// 3. Object.create()
// ===========================================
console.log("\n=== 3. Object.create() ===");
const dinoPrototype = {
getInfo() {
return `${this.name} (${this.species})`;
},
roar() {
return `${this.name}: ROAARRR!`;
}
};
const velociraptor = Object.create(dinoPrototype);
velociraptor.name = "Charlie";
velociraptor.species = "Velociraptor";
velociraptor.age = 5;
console.log("\nUtworzono przez Object.create():");
console.log(` ${velociraptor.getInfo()}`);
console.log(` ${velociraptor.roar()}`);
// ===========================================
// 4. KLASY ES6
// ===========================================
console.log("\n=== 4. Klasy ES6 ===");
class DinosaurClass {
constructor(name, species, age, weight, carnivore) {
this.name = name;
this.species = species;
this.age = age;
this.weight = weight;
this.carnivore = carnivore;
}
getInfo() {
return `${this.name} (${this.species}) - ${this.age} lat, ${this.weight}kg`;
}
roar() {
return `${this.name} says: ROAARRR!`;
}
isHeavy() {
return this.weight > 1000;
}
}
const stego = new DinosaurClass("Stego", "Stegosaurus", 6, 5000, false);
const brachio = new DinosaurClass("Brachio", "Brachiosaurus", 10, 50000, false);
console.log("\nUtworzono przez klasę:");
console.log(` ${stego.getInfo()}`);
console.log(` Czy ciężki? ${stego.isHeavy()}`);
console.log(` ${brachio.getInfo()}`);
console.log(` Czy ciężki? ${brachio.isHeavy()}`);
// ===========================================
// 5. FACTORY FUNCTIONS
// ===========================================
console.log("\n=== 5. Factory functions ===");
function createDinosaur(name, species, options = {}) {
return {
name,
species,
age: options.age || 5,
weight: options.weight || 100,
carnivore: options.carnivore || false,
sector: options.sector || "A",
getInfo() {
return `${this.name} (${this.species}) - Sektor ${this.sector}`;
},
feed() {
console.log(`Karmienie ${this.name}`);
}
};
}
const dilo = createDinosaur("Dilo", "Dilophosaurus", {
age: 4,
weight: 400,
carnivore: true,
sector: "E"
});
console.log("\nUtworzono przez factory:");
console.log(` ${dilo.getInfo()}`);
dilo.feed();
// ===========================================
// 6. OBIEKTY ZAGNIEŻDŻONE
// ===========================================
console.log("\n=== 6. Obiekty zagnieżdżone ===");
const park = {
name: "Jurassic Park",
location: "Isla Nublar",
sectors: {
A: { name: "Carnivore Zone", capacity: 5, current: 2 },
B: { name: "Raptor Pen", capacity: 10, current: 3 },
C: { name: "Herbivore Valley", capacity: 20, current: 8 }
},
stats: {
totalDinosaurs: 13,
totalVisitors: 1500,
securityLevel: "HIGH"
},
getReport() {
console.log(`\nRaport parku ${this.name}:`);
console.log(` Lokalizacja: ${this.location}`);
console.log(` Dinozaury: ${this.stats.totalDinosaurs}`);
console.log(` Odwiedzający: ${this.stats.totalVisitors}`);
console.log(` Bezpieczeństwo: ${this.stats.securityLevel}`);
}
};
park.getReport();
console.log("\nSektory:");
Object.entries(park.sectors).forEach(([key, sector]) => {
console.log(` ${key}: ${sector.name} - ${sector.current}/${sector.capacity}`);
});
// ===========================================
// 7. GETTERY I SETTERY
// ===========================================
console.log("\n=== 7. Gettery i settery ===");
class ManagedDinosaur {
constructor(name, species, health) {
this.name = name;
this.species = species;
this._health = health; // Prywatna właściwość (konwencja)
}
// Getter
get health() {
return this._health;
}
// Setter z walidacją
set health(value) {
if (value < 0) value = 0;
if (value > 100) value = 100;
this._health = value;
console.log(` Zdrowie ${this.name} zmienione na ${this._health}%`);
}
get status() {
if (this._health >= 80) return "Zdrowy";
if (this._health >= 50) return "Średni";
return "Krytyczny";
}
}
const managedDino = new ManagedDinosaur("Rex", "T-Rex", 75);
console.log(`\n${managedDino.name}:`);
console.log(` Zdrowie: ${managedDino.health}%`);
console.log(` Status: ${managedDino.status}`);
managedDino.health = 95;
console.log(` Nowy status: ${managedDino.status}`);
managedDino.health = 150; // Będzie ograniczone do 100
console.log(` Status po przekroczeniu: ${managedDino.status}`);
// ===========================================
// 8. STATYCZNE METODY I WŁAŚCIWOŚCI
// ===========================================
console.log("\n=== 8. Statyczne metody i właściwości ===");
class DinoSpecies {
static species = [
"Tyrannosaurus Rex",
"Velociraptor",
"Triceratops",
"Stegosaurus",
"Brachiosaurus"
];
static isCarnivore(species) {
const carnivores = ["Tyrannosaurus Rex", "Velociraptor", "Spinosaurus"];
return carnivores.includes(species);
}
static getInfo(species) {
const info = {
"Tyrannosaurus Rex": { weight: 8000, period: "Kredowy" },
"Velociraptor": { weight: 80, period: "Kredowy" },
"Triceratops": { weight: 9000, period: "Kredowy" }
};
return info[species] || { weight: "?", period: "?" };
}
static listAll() {
console.log("\nWszystkie gatunki:");
this.species.forEach((s, i) => {
const carnivore = this.isCarnivore(s) ? "mięsożerca" : "roślinożerca";
console.log(` ${i + 1}. ${carnivore} ${s}`);
});
}
}
DinoSpecies.listAll();
console.log("\nSprawdzanie gatunków:");
console.log(` T-Rex mięsożerca? ${DinoSpecies.isCarnivore("Tyrannosaurus Rex")}`);
console.log(` Triceratops mięsożerca? ${DinoSpecies.isCarnivore("Triceratops")}`);
const trexInfo = DinoSpecies.getInfo("Tyrannosaurus Rex");
console.log(`\nInfo o T-Rex: waga ${trexInfo.weight}kg, okres ${trexInfo.period}`);
// ===========================================
// 9. DZIEDZICZENIE
// ===========================================
console.log("\n=== 9. Dziedziczenie ===");
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
breathe() {
return `${this.name} oddycha`;
}
getAge() {
return `${this.name} ma ${this.age} lat`;
}
}
class Carnivore extends Animal {
constructor(name, age, huntingSkill) {
super(name, age);
this.huntingSkill = huntingSkill;
this.type = "Mięsożerca";
}
hunt() {
return `${this.name} poluje (umiejętność: ${this.huntingSkill}/10)`;
}
roar() {
return `${this.name} ryczy: ROAARRR!`;
}
}
class Herbivore extends Animal {
constructor(name, age, plantPreference) {
super(name, age);
this.plantPreference = plantPreference;
this.type = "Roślinożerca";
}
eat() {
return `${this.name} je ${this.plantPreference}`;
}
graze() {
return `${this.name} spokojnie się pasie`;
}
}
const rex = new Carnivore("Rexy", 8, 10);
const trico = new Herbivore("Trico", 7, "paprocie");
console.log("\nMięsożerca:");
console.log(` ${rex.getAge()}`);
console.log(` ${rex.breathe()}`);
console.log(` ${rex.hunt()}`);
console.log(` ${rex.roar()}`);
console.log("\nRoślinożerca:");
console.log(` ${trico.getAge()}`);
console.log(` ${trico.breathe()}`);
console.log(` ${trico.eat()}`);
console.log(` ${trico.graze()}`);
// ===========================================
// 10. PRZYKŁAD KOMPLEKSOWY
// ===========================================
console.log("\n=== 10. System zarządzania - przykład kompleksowy ===");
class ParkManagementSystem {
constructor(parkName) {
this.parkName = parkName;
this.dinosaurs = new Map();
this.nextId = 1;
}
addDinosaur(name, species, options = {}) {
const dino = {
id: this.nextId++,
name,
species,
age: options.age || 5,
weight: options.weight || 1000,
health: options.health || 100,
sector: options.sector || "A",
carnivore: options.carnivore || false,
fed: false,
lastCheckup: new Date()
};
this.dinosaurs.set(dino.id, dino);
console.log(`Dodano: ${name} (#${dino.id})`);
return dino.id;
}
getDinosaur(id) {
return this.dinosaurs.get(id);
}
removeDinosaur(id) {
const dino = this.dinosaurs.get(id);
if (dino) {
this.dinosaurs.delete(id);
console.log(`Usunięto: ${dino.name} (#${id})`);
return true;
}
return false;
}
feedDinosaur(id) {
const dino = this.dinosaurs.get(id);
if (dino) {
dino.fed = true;
console.log(`Nakarmiono: ${dino.name}`);
}
}
updateHealth(id, newHealth) {
const dino = this.dinosaurs.get(id);
if (dino) {
dino.health = Math.max(0, Math.min(100, newHealth));
console.log(`Zaktualizowano zdrowie ${dino.name}: ${dino.health}%`);
}
}
getStats() {
const dinos = Array.from(this.dinosaurs.values());
return {
total: dinos.length,
carnivores: dinos.filter(d => d.carnivore).length,
avgHealth: (dinos.reduce((sum, d) => sum + d.health, 0) / dinos.length).toFixed(1),
fed: dinos.filter(d => d.fed).length,
bySector: dinos.reduce((acc, d) => {
acc[d.sector] = (acc[d.sector] || 0) + 1;
return acc;
}, {})
};
}
displayReport() {
console.log(`\n============================================================`);
console.log(`RAPORT PARKU: ${this.parkName}`);
console.log("=".repeat(60));
const stats = this.getStats();
console.log("\nStatystyki:");
console.log(` Łącznie dinozaurów: ${stats.total}`);
console.log(` Mięsożercy: ${stats.carnivores}`);
console.log(` Średnie zdrowie: ${stats.avgHealth}%`);
console.log(` Nakarmione: ${stats.fed}/${stats.total}`);
console.log("\nPodział na sektory:");
Object.entries(stats.bySector).sort().forEach(([sector, count]) => {
console.log(` Sektor ${sector}: ${count}`);
});
console.log("\nLista dinozaurów:");
Array.from(this.dinosaurs.values())
.sort((a, b) => a.id - b.id)
.forEach(dino => {
const icon = dino.carnivore ? "mięsożerca" : "roślinożerca";
const fedStatus = dino.fed ? "√" : "×";
console.log(` #${dino.id} ${icon} ${dino.name} (${dino.species})`);
console.log(` Sektor ${dino.sector} | Zdrowie: ${dino.health}% | Nakarmiony: ${fedStatus}`);
});
}
}
// Demonstracja systemu
console.log();
const parkSystem = new ParkManagementSystem("Isla Nublar");
const id1 = parkSystem.addDinosaur("Rexy", "T-Rex", { age: 8, weight: 8000, sector: "A", carnivore: true });
const id2 = parkSystem.addDinosaur("Blue", "Velociraptor", { age: 5, weight: 80, sector: "B", carnivore: true, health: 100 });
const id3 = parkSystem.addDinosaur("Charlie", "Velociraptor", { age: 5, weight: 80, sector: "B", carnivore: true, health: 85 });
const id4 = parkSystem.addDinosaur("Trike", "Triceratops", { age: 7, weight: 9000, sector: "C", health: 70 });
const id5 = parkSystem.addDinosaur("Stego", "Stegosaurus", { age: 6, weight: 5000, sector: "C" });
console.log();
parkSystem.feedDinosaur(id1);
parkSystem.feedDinosaur(id2);
parkSystem.updateHealth(id4, 85);
parkSystem.displayReport();
console.log("\nGratulacje! Opanowałeś tworzenie obiektów!");Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Jakie są dwa sposoby dostępu do właściwości obiektu w JavaScript?
2. Co robi słowo kluczowe 'new' przed wywołaniem funkcji konstruktora?
Zadania praktyczne w grze
- Klikanie w kolejności
Ułóż elementy tworzenia obiektu dinozaura z metodą:
- Edytor kodu
Utwórz obiekt dinosaur z właściwościami name: 'Rexy', species: 'Tyrannosaurus Rex', age: 25 i isCarnivore: true oraz z zagnieżdżonym obiektem stats, który ma właściwość health: 95. Po utworzeniu obiektu dodaj do niego właściwość enclosure o wartości 'Zone A'. Wyświetl w konsoli name w notacji kropkowej i species w notacji nawiasowej.
- Układanie w poziomie
Ułóż elementy tworzenia obiektu literałem:
- Klikanie w kolejności
Ułóż elementy deklaracji obiektu z właściwościami:
- Układanie w poziomie
Ułóż elementy deklaracji obiektu w JavaScript
Zadania po tej lekcji
- PytaniePodstawy obiektów - dostęp do właściwości
- PytaniePodstawy obiektów - konstruktor z new
- Kliknij w kolejnościPodstawy obiektów - tworzenie literałem
- Zadanie z kodemTworzenie obiektów
- Ułóż w kolejnościLiterał obiektowy
- Kliknij w kolejnościSortowanie: Deklaracja obiektu
- Ułóż w kolejnościSkładnia literału obiektowego