Kurs JavaScript i TypeScript · Moduł 2: Funkcje, tablice i obiekty

Prototypy i dziedziczenie prototypowe

15 min czytania ·
W tej lekcji12

W Parku Jurajskim efektywne zarządzanie różnymi gatunkami dinozaurów wymaga zrozumienia podobieństw między nimi i możliwości dziedziczenia cech. JavaScript używa prototypów do implementacji mechanizmu dziedziczenia - jest to jeden z najbardziej unikalnych i potężnych aspektów tego języka. Zrozumienie prototypów i dziedziczenia prototypowego jest kluczowe dla pisania wydajnego, elastycznego kodu JavaScript.

Czym są prototypy?

W JavaScript każdy obiekt ma wewnętrzną właściwość zwaną prototypem, która jest referencją do innego obiektu. Gdy próbujemy uzyskać dostęp do właściwości obiektu, JavaScript najpierw sprawdza, czy sam obiekt posiada taką właściwość. Jeśli nie, sprawdza prototyp obiektu, następnie prototyp prototypu, itd., tworząc tzw. łańcuch prototypów.

// Tworzymy prosty obiekt
const dinosaur = {
  species: "Tyrannosaurus",
  makesSound: true,
  roar() {
    return "ROOOOAR!";
  }
};

// Tworzymy nowy obiekt, który dziedziczy po obiekcie dinosaur
const rex = Object.create(dinosaur);
rex.name = "Rex";
rex.age = 8;

// rex ma dostęp do swoich własnych właściwości
console.log(rex.name); // "Rex"
console.log(rex.age); // 8

// rex ma również dostęp do właściwości i metod dinosaur
console.log(rex.species); // "Tyrannosaurus"
console.log(rex.makesSound); // true
console.log(rex.roar()); // "ROOOOAR!"

// Sprawdźmy, czy rex ma własną właściwość 'species' (nie ma)
console.log(rex.hasOwnProperty('species')); // false

// Ale ma własną właściwość 'name'
console.log(rex.hasOwnProperty('name')); // true

W powyższym przykładzie rex nie ma własnej właściwości species, ale dostęp do rex.species działa, ponieważ JavaScript szuka tej właściwości w prototypie rex, którym jest obiekt dinosaur.

Łańcuch prototypów

Prototypy tworzą łańcuch, który JavaScript przeszukuje, gdy próbujemy uzyskać dostęp do właściwości. Ten mechanizm nazywamy łańcuchem prototypów (prototype chain).

// Podstawowy obiekt przodek
const animal = {
  isAlive: true,
  eat() {
    return `${this.name} je.`;
  }
};

// Obiekt dinozaur dziedziczący po animal
const dinosaur = Object.create(animal);
dinosaur.isExtinct = false;
dinosaur.roar = function() {
  return `${this.name} ryczy!`;
};

// Konkretny gatunek dinozaura dziedziczący po dinosaur
const tyrannosaurus = Object.create(dinosaur);
tyrannosaurus.name = "Tyrannosaurus";
tyrannosaurus.diet = "carnivore";
tyrannosaurus.length = 12; // metry

// tyrannosaurus ma dostęp do właściwości wszystkich prototypów w łańcuchu
console.log(tyrannosaurus.name); // "Tyrannosaurus" (własna właściwość)
console.log(tyrannosaurus.isExtinct); // false (z dinosaur)
console.log(tyrannosaurus.isAlive); // true (z animal)
console.log(tyrannosaurus.eat()); // "Tyrannosaurus je." (metoda z animal, this odwołuje się do tyrannosaurus)
console.log(tyrannosaurus.roar()); // "Tyrannosaurus ryczy!" (metoda z dinosaur)

Konstruktory i prototypy

W praktyce, prototypy są najczęściej używane z konstruktorami i klasami do implementowania dziedziczenia w JavaScript.

Funkcje konstruktora i prototypy

Każda funkcja konstruktora ma właściwość prototype, która jest używana jako prototyp dla obiektów tworzonych za pomocą tej funkcji z operatorem new.

// Funkcja konstruktora dla Dinosaur
function Dinosaur(name, species, diet) {
  this.name = name;
  this.species = species;
  this.diet = diet;
  this.isExtinct = false;
}

// Dodajemy metody do prototypu Dinosaur
Dinosaur.prototype.roar = function() {
  const volume = this.diet === "carnivore" ? "głośno" : "cicho";
  return `${this.name} ryczy ${volume}!`;
};

Dinosaur.prototype.describe = function() {
  return `${this.name} to ${this.species}, który jest ${this.diet === "carnivore" ? "mięsożerny" : "roślinożerny"}.`;
};

// Tworzymy instancje
const trex = new Dinosaur("Rex", "Tyrannosaurus", "carnivore");
const tricera = new Dinosaur("Trixie", "Triceratops", "herbivore");

console.log(trex.roar()); // "Rex ryczy głośno!"
console.log(tricera.roar()); // "Trixie ryczy cicho!"
console.log(trex.describe()); // "Rex to Tyrannosaurus, który jest mięsożerny."

// Wszystkie instancje współdzielą te same metody prototypu
console.log(trex.roar === tricera.roar); // true

W tym przykładzie, metody roar i describe są definiowane na prototypie funkcji konstruktora Dinosaur. Wszystkie instancje utworzone za pomocą new Dinosaur() współdzielą te same metody, co jest znacznie bardziej efektywne niż definiowanie tych metod w konstruktorze dla każdej instancji osobno.

Sprawdzanie prototypu obiektu

Możemy sprawdzić prototyp obiektu za pomocą kilku metod:

// Używając Object.getPrototypeOf()
console.log(Object.getPrototypeOf(trex) === Dinosaur.prototype); // true

// Używając __proto__ (właściwość przestarzała, nie zalecana w kodzie produkcyjnym)
console.log(trex.__proto__ === Dinosaur.prototype); // true

// Sprawdzanie, czy obiekt jest instancją konstruktora
console.log(trex instanceof Dinosaur); // true
console.log(trex instanceof Object); // true (wszystkie obiekty dziedziczą po Object.prototype)

Dziedziczenie między konstruktorami

Możemy implementować dziedziczenie między funkcjami konstruktora, łącząc ich prototypy:

// Funkcja konstruktora dla Animal (klasa bazowa)
function Animal(name) {
  this.name = name;
  this.isAlive = true;
}

Animal.prototype.eat = function(food) {
  return `${this.name} je ${food}.`;
};

Animal.prototype.sleep = function() {
  return `${this.name} śpi.`;
};

// Funkcja konstruktora dla Dinosaur (klasa pochodna)
function Dinosaur(name, species, diet) {
  // Wywołujemy konstruktor klasy bazowej
  Animal.call(this, name);

  // Dodajemy właściwości specyficzne dla Dinosaur
  this.species = species;
  this.diet = diet;
  this.isExtinct = false;
}

// Ustawiamy prototyp Dinosaur, aby dziedziczył po Animal.prototype
Dinosaur.prototype = Object.create(Animal.prototype);

// Przywracamy właściwą właściwość konstruktora
Dinosaur.prototype.constructor = Dinosaur;

// Dodajemy metody specyficzne dla Dinosaur
Dinosaur.prototype.roar = function() {
  const volume = this.diet === "carnivore" ? "głośno" : "cicho";
  return `${this.name} ryczy ${volume}!`;
};

// Tworzymy instancję Dinosaur
const velociraptor = new Dinosaur("Blue", "Velociraptor", "carnivore");

// Mamy dostęp do metod z Animal
console.log(velociraptor.eat("mięso")); // "Blue je mięso."
console.log(velociraptor.sleep()); // "Blue śpi."

// Oraz do metod specyficznych dla Dinosaur
console.log(velociraptor.roar()); // "Blue ryczy głośno!"

// Sprawdzamy łańcuch prototypów
console.log(velociraptor instanceof Dinosaur); // true
console.log(velociraptor instanceof Animal); // true
console.log(velociraptor instanceof Object); // true

Ten wzorzec implementacji dziedziczenia między konstruktorami jest często nazywany "dziedziczeniem pseudoklasycznym", ponieważ emuluje dziedziczenie klasowe w języku, który oryginalnie bazuje na prototypach.

Dziedziczenie wielopoziomowe

Możemy tworzyć wielopoziomowe hierarchie dziedziczenia, łącząc łańcuchy prototypów:

// Klasa bazowa Animal
function Animal(name) {
  this.name = name;
  this.isAlive = true;
}

Animal.prototype.breathe = function() {
  return `${this.name} oddycha.`;
};

// Klasa Dinosaur dziedzicząca po Animal
function Dinosaur(name, period) {
  Animal.call(this, name);
  this.period = period;
  this.extinct = true;
}

Dinosaur.prototype = Object.create(Animal.prototype);
Dinosaur.prototype.constructor = Dinosaur;

Dinosaur.prototype.roar = function() {
  return `${this.name} ryczy!`;
};

// Klasa Theropod (teropod) dziedzicząca po Dinosaur
function Theropod(name, period, speed) {
  Dinosaur.call(this, name, period);
  this.speed = speed; // km/h
  this.bipedal = true;
}

Theropod.prototype = Object.create(Dinosaur.prototype);
Theropod.prototype.constructor = Theropod;

Theropod.prototype.run = function() {
  return `${this.name} biegnie z prędkością ${this.speed} km/h!`;
};

// Klasa Tyrannosaurus dziedzicząca po Theropod
function Tyrannosaurus(name, size) {
  Theropod.call(this, name, "Late Cretaceous", 30);
  this.size = size;
  this.teeth = 60;
}

Tyrannosaurus.prototype = Object.create(Theropod.prototype);
Tyrannosaurus.prototype.constructor = Tyrannosaurus;

Tyrannosaurus.prototype.bite = function() {
  return `${this.name} gryzie z ogromną siłą dzięki ${this.teeth} zębom!`;
};

// Tworzymy instancję Tyrannosaurus
const rex = new Tyrannosaurus("Rex", "bardzo duży");

// Mamy dostęp do metod wszystkich prototypów w łańcuchu
console.log(rex.breathe()); // "Rex oddycha." (z Animal)
console.log(rex.roar()); // "Rex ryczy!" (z Dinosaur)
console.log(rex.run()); // "Rex biegnie z prędkością 30 km/h!" (z Theropod)
console.log(rex.bite()); // "Rex gryzie z ogromną siłą dzięki 60 zębom!" (z Tyrannosaurus)

// Sprawdzamy łańcuch prototypów
console.log(rex instanceof Tyrannosaurus); // true
console.log(rex instanceof Theropod); // true
console.log(rex instanceof Dinosaur); // true
console.log(rex instanceof Animal); // true
console.log(rex instanceof Object); // true

Prototypy a klasy w ES6+

ES6 wprowadził składnię klas, która pod spodem używa prototypów, ale oferuje bardziej przyjazną, podobną do klasycznej obiektowości składnię:

// Klasa bazowa Animal
class Animal {
  constructor(name) {
    this.name = name;
    this.isAlive = true;
  }

  eat(food) {
    return `${this.name} je ${food}.`;
  }

  sleep() {
    return `${this.name} śpi.`;
  }
}

// Klasa Dinosaur dziedzicząca po Animal
class Dinosaur extends Animal {
  constructor(name, species, diet) {
    super(name); // Wywołanie konstruktora klasy bazowej
    this.species = species;
    this.diet = diet;
    this.isExtinct = false;
  }

  roar() {
    const volume = this.diet === "carnivore" ? "głośno" : "cicho";
    return `${this.name} ryczy ${volume}!`;
  }

  // Nadpisujemy metodę eat z klasy bazowej
  eat(food) {
    if (this.diet === "carnivore" && food === "mięso") {
      return `${this.name} z apetytem pożera ${food}!`;
    } else if (this.diet === "herbivore" && food === "rośliny") {
      return `${this.name} spokojnie skubie ${food}.`;
    } else {
      return `${this.name} nie jest zainteresowany jedzeniem ${food}.`;
    }
  }
}

// Klasa pochodna Velociraptor dziedzicząca po Dinosaur
class Velociraptor extends Dinosaur {
  constructor(name, speed) {
    super(name, "Velociraptor", "carnivore");
    this.speed = speed;
    this.packHunter = true;
  }

  hunt() {
    return `${this.name} poluje w grupie z prędkością ${this.speed} km/h!`;
  }
}

// Tworzymy instancje
const blue = new Velociraptor("Blue", 70);

console.log(blue.eat("mięso")); // "Blue z apetytem pożera mięso!"
console.log(blue.sleep()); // "Blue śpi."
console.log(blue.roar()); // "Blue ryczy głośno!"
console.log(blue.hunt()); // "Blue poluje w grupie z prędkością 70 km/h!"

// Sprawdzamy łańcuch prototypów
console.log(blue instanceof Velociraptor); // true
console.log(blue instanceof Dinosaur); // true
console.log(blue instanceof Animal); // true
console.log(blue instanceof Object); // true

Składnia klas w ES6 jest tylko "cukrem składniowym" (syntactic sugar) nad istniejącym mechanizmem prototypów w JavaScript. Pod spodem, JavaScript nadal używa prototypów do implementacji dziedziczenia.

Wielodziedziczenie i miksy (mixins)

JavaScript nie obsługuje bezpośrednio wielodziedziczenia (dziedziczenia po wielu klasach jednocześnie), ale możemy używać wzorca "mixins" do uzyskania podobnego efektu:

// Klasa bazowa
class Dinosaur {
  constructor(name, species) {
    this.name = name;
    this.species = species;
  }

  roar() {
    return `${this.name} ryczy!`;
  }
}

// Mixin dla zachowań drapieżnych (carnivore behavior)
const CarnivoreMixin = {
  hunt(prey) {
    return `${this.name} poluje na ${prey}!`;
  },

  bite() {
    return `${this.name} gryzie z dużą siłą!`;
  }
};

// Mixin dla zachowań związanych ze stadnym polowaniem (pack hunting behavior)
const PackHunterMixin = {
  coordinateAttack() {
    return `${this.name} koordynuje atak stada!`;
  },

  communicateWithPack() {
    return `${this.name} komunikuje się z innymi członkami stada.`;
  }
};

// Mixin dla zachowań związanych z terytorium (territorial behavior)
const TerritorialMixin = {
  markTerritory() {
    return `${this.name} zaznacza swoje terytorium.`;
  },

  defendTerritory(intruder) {
    return `${this.name} broni swojego terytorium przed ${intruder}!`;
  }
};

// Funkcja do aplikowania mixinów do klasy
function applyMixins(targetClass, ...mixins) {
  mixins.forEach(mixin => {
    Object.getOwnPropertyNames(mixin).forEach(name => {
      if (name !== 'constructor') {
        targetClass.prototype[name] = mixin[name];
      }
    });
  });
}

// Klasa Velociraptor z kilkoma mixinami
class Velociraptor extends Dinosaur {
  constructor(name) {
    super(name, "Velociraptor");
    this.diet = "carnivore";
    this.speed = 70; // km/h
  }
}

// Aplikujemy mixiny do Velociraptor
applyMixins(Velociraptor, CarnivoreMixin, PackHunterMixin, TerritorialMixin);

// Tworzymy instancję Velociraptor
const blue = new Velociraptor("Blue");

// Teraz blue ma dostęp do metod z różnych mixinów
console.log(blue.roar()); // "Blue ryczy!" (z Dinosaur)
console.log(blue.hunt("Gallimimus")); // "Blue poluje na Gallimimus!" (z CarnivoreMixin)
console.log(blue.bite()); // "Blue gryzie z dużą siłą!" (z CarnivoreMixin)
console.log(blue.coordinateAttack()); // "Blue koordynuje atak stada!" (z PackHunterMixin)
console.log(blue.defendTerritory("Tyrannosaurus")); // "Blue broni swojego terytorium przed Tyrannosaurus!" (z TerritorialMixin)

Mixiny pozwalają na "mieszanie" funkcjonalności z różnych źródeł bez konieczności stosowania wielodziedziczenia, którego JavaScript formalnie nie obsługuje.

Object.prototype

Wszystkie obiekty w JavaScript ostatecznie dziedziczą po Object.prototype. Zawiera on wiele przydatnych metod, takich jak toString(), hasOwnProperty(), valueOf(), itp.

const dino = { name: "Rex" };

// dino dziedziczy metody z Object.prototype
console.log(dino.toString()); // "[object Object]"
console.log(dino.hasOwnProperty("name")); // true
console.log(dino.hasOwnProperty("age")); // false

// Możemy nadpisać metody z Object.prototype
dino.toString = function() {
  return `Dinozaur: ${this.name}`;
};

console.log(dino.toString()); // "Dinozaur: Rex"

Dziedziczenie prototypowe w praktyce: System dinozaurów Parku Jurajskiego

Poniżej znajduje się przykład bardziej złożonego systemu zarządzania dinozaurami, wykorzystującego dziedziczenie prototypowe:

// Podstawowa klasa dla wszystkich istot w parku
class Creature {
  constructor(name, age) {
    this.name = name;
    this.age = age;
    this.health = 100;
    this.alive = true;
  }

  eat(food) {
    this.health = Math.min(100, this.health + 10);
    return `${this.name} je ${food}. Zdrowie: ${this.health}%`;
  }

  sleep() {
    this.health = Math.min(100, this.health + 5);
    return `${this.name} śpi. Zdrowie: ${this.health}%`;
  }

  damage(amount) {
    this.health = Math.max(0, this.health - amount);
    if (this.health === 0 && this.alive) {
      this.alive = false;
      return `${this.name} nie żyje!`;
    }
    return `${this.name} otrzymuje ${amount} obrażeń. Pozostałe zdrowie: ${this.health}%`;
  }
}

// Klasa dla dinozaurów, dziedzicząca po Creature
class Dinosaur extends Creature {
  constructor(name, species, age, diet) {
    super(name, age);
    this.species = species;
    this.diet = diet;
    this.containmentLevel = this.calculateContainmentLevel();
  }

  calculateContainmentLevel() {
    if (this.diet === "carnivore") {
      return this.age > 5 ? "Maximum" : "High";
    } else {
      return this.age > 10 ? "Medium" : "Standard";
    }
  }

  roar() {
    const volume = this.diet === "carnivore" ? "głośno" : "cicho";
    return `${this.name} ryczy ${volume}!`;
  }

  getStatus() {
    return `
Dinozaur: ${this.name} (${this.species})
Wiek: ${this.age} lat
Dieta: ${this.diet === "carnivore" ? "Mięsożerna" : "Roślinożerna"}
Zdrowie: ${this.health}%
Status: ${this.alive ? "Żywy" : "Nieżywy"}
Poziom bezpieczeństwa: ${this.containmentLevel}
`;
  }
}

// Klasa dla mięsożernych dinozaurów (drapieżników)
class Carnivore extends Dinosaur {
  constructor(name, species, age, attackPower) {
    super(name, species, age, "carnivore");
    this.attackPower = attackPower;
    this.huntingSuccess = 0.7; // 70% szans na udane polowanie
  }

  hunt(prey) {
    if (!this.alive) return `${this.name} nie żyje, nie może polować.`;
    if (!prey.alive) return `${prey.name} jest już martwy.`;

    const huntSuccess = Math.random() < this.huntingSuccess;

    if (huntSuccess) {
      const damage = Math.floor(this.attackPower * (0.7 + Math.random() * 0.6)); // 70-130% mocy ataku
      const result = prey.damage(damage);
      this.eat("mięso");
      return `${this.name} skutecznie poluje na ${prey.name}! ${result}`;
    } else {
      return `${this.name} próbuje upolować ${prey.name}, ale nie udaje się.`;
    }
  }

  clawAttack(target) {
    if (!this.alive) return `${this.name} nie żyje, nie może atakować.`;
    if (!target.alive) return `${target.name} jest już martwy.`;

    const damage = Math.floor(this.attackPower * 0.6);
    const result = target.damage(damage);
    return `${this.name} atakuje ${target.name} pazurami! ${result}`;
  }

  biteAttack(target) {
    if (!this.alive) return `${this.name} nie żyje, nie może atakować.`;
    if (!target.alive) return `${target.name} jest już martwy.`;

    const damage = Math.floor(this.attackPower * 1.2);
    const result = target.damage(damage);
    return `${this.name} gryzie ${target.name}! ${result}`;
  }
}

// Klasa dla roślinożernych dinozaurów
class Herbivore extends Dinosaur {
  constructor(name, species, age, defenseRating) {
    super(name, species, age, "herbivore");
    this.defenseRating = defenseRating;
    this.fleeSuccess = 0.6; // 60% szans na udaną ucieczkę
  }

  grazeVegetation() {
    if (!this.alive) return `${this.name} nie żyje, nie może jeść.`;

    this.health = Math.min(100, this.health + 15);
    return `${this.name} skubie rośliny. Zdrowie wzrasta do ${this.health}%.`;
  }

  flee(predator) {
    if (!this.alive) return `${this.name} nie żyje, nie może uciekać.`;

    const escapeSuccess = Math.random() < this.fleeSuccess;

    if (escapeSuccess) {
      this.health = Math.max(0, this.health - 5); // Ucieczka kosztuje energię
      return `${this.name} skutecznie ucieka przed ${predator.name}!`;
    } else {
      return `${this.name} próbuje uciec przed ${predator.name}, ale nie udaje się.`;
    }
  }

  // Defensywna metoda - zmniejsza otrzymane obrażenia
  damage(amount) {
    // Roślinożercy otrzymują mniej obrażeń dzięki defenseRating
    const reducedDamage = Math.max(0, amount - this.defenseRating);
    return super.damage(reducedDamage);
  }
}

// Specyficzne gatunki dinozaurów
class Tyrannosaurus extends Carnivore {
  constructor(name, age) {
    super(name, "Tyrannosaurus Rex", age, 35);
    this.intimidationFactor = 9;
    this.territorialRange = 5; // km
  }

  intimidate(target) {
    return `${this.name} wydaje ogłuszający ryk, który przeraża ${target.name}!`;
  }

  // Nadpisujemy metodę roar
  roar() {
    return `${this.name} wydaje potężny, ogłuszający ryk, który rozchodzi się na kilometry!`;
  }
}

class Velociraptor extends Carnivore {
  constructor(name, age) {
    super(name, "Velociraptor", age, 20);
    this.speed = 70; // km/h
    this.intelligence = 9;
    this.packHunting = true;
  }

  coordinateAttack(targets) {
    if (!Array.isArray(targets) || targets.length < 2) {
      return `${this.name} potrzebuje co najmniej dwóch celów do koordynacji ataku.`;
    }

    let results = `${this.name} koordynuje atak stada na ${targets.map(t => t.name).join(', ')}!\n`;
    targets.forEach(target => {
      const damage = Math.floor(this.attackPower * 1.5); // Wzmocniony atak stadny
      results += target.damage(damage) + '\n';
    });

    return results;
  }

  ambush(target) {
    const damage = Math.floor(this.attackPower * 2); // Podwójne obrażenia z zasadzki
    const result = target.damage(damage);
    return `${this.name} urządza zasadzkę na ${target.name}! ${result}`;
  }
}

class Triceratops extends Herbivore {
  constructor(name, age) {
    super(name, "Triceratops", age, 25);
    this.hornStrength = 30;
  }

  chargeAttack(target) {
    const damage = this.hornStrength + Math.floor(Math.random() * 10);
    const result = target.damage(damage);
    return `${this.name} szarżuje na ${target.name} swoimi rogami! ${result}`;
  }

  defendFromAttack(attacker) {
    const counterDamage = Math.floor(this.hornStrength * 0.5);
    const result = attacker.damage(counterDamage);
    return `${this.name} broni się przed ${attacker.name} używając swoich rogów! ${result}`;
  }
}

class Brachiosaurus extends Herbivore {
  constructor(name, age) {
    super(name, "Brachiosaurus", age, 15);
    this.height = 13; // metry
    this.tailLength = 9; // metry
  }

  reachHighVegetation() {
    this.health = Math.min(100, this.health + 20);
    return `${this.name} sięga swoją długą szyją po liście wysokich drzew. Zdrowie wzrasta do ${this.health}%.`;
  }

  tailWhip(target) {
    const damage = Math.floor(this.tailLength * 2);
    const result = target.damage(damage);
    return `${this.name} uderza ${target.name} swoim ogromnym ogonem! ${result}`;
  }
}

// Symulacja parku jurajskiego
function runJurassicParkSimulation() {
  console.log("=== SYMULACJA PARKU JURAJSKIEGO ===\n");

  // Tworzenie dinozaurów
  const rex = new Tyrannosaurus("Rex", 8);
  const blue = new Velociraptor("Blue", 4);
  const delta = new Velociraptor("Delta", 4);
  const trixie = new Triceratops("Trixie", 12);
  const bronty = new Brachiosaurus("Bronty", 25);

  // Wyświetlanie informacji o dinozaurach
  console.log(rex.getStatus());
  console.log(blue.getStatus());
  console.log(trixie.getStatus());
  console.log(bronty.getStatus());

  console.log("\n=== INTERAKCJE DINOZAURÓW ===\n");

  // Interakcje między dinozaurami
  console.log(rex.roar());
  console.log(blue.roar());
  console.log(trixie.grazeVegetation());
  console.log(bronty.reachHighVegetation());

  console.log("\n=== POJEDYNEK: REX VS TRIXIE ===\n");

  console.log(rex.intimidate(trixie));
  console.log(trixie.flee(rex));
  console.log(rex.hunt(trixie));
  console.log(trixie.defendFromAttack(rex));
  console.log(rex.biteAttack(trixie));

  console.log("\n=== POLOWANIE STADA VELOCIRAPTORÓW ===\n");

  console.log(blue.coordinateAttack([trixie, bronty]));
  console.log(delta.ambush(bronty));
  console.log(bronty.tailWhip(delta));

  console.log("\n=== STAN DINOZAURÓW PO INTERAKCJACH ===\n");

  console.log(rex.getStatus());
  console.log(blue.getStatus());
  console.log(delta.getStatus());
  console.log(trixie.getStatus());
  console.log(bronty.getStatus());
}

// Uruchomienie symulacji
runJurassicParkSimulation();

Dziedziczenie prototypowe vs klasyczne dziedziczenie

Dziedziczenie prototypowe w JavaScript różni się od klasycznego dziedziczenia w innych językach obiektowych:

  1. Dynamiczność - prototypy mogą być modyfikowane w czasie wykonania programu, podczas gdy klasy są zwykle statyczne.
  2. Łańcuch prototypów - właściwości są wyszukiwane w łańcuchu prototypów, podczas gdy w klasycznym dziedziczeniu metody są rozwiązywane przez hierarchię klas.
  3. Brak klas (przed ES6) - JavaScript tradycyjnie nie miał formalnej koncepcji klas, a jedynie funkcje konstruktora i prototypy.
  4. Dziedziczenie pojedyncze - JavaScript obsługuje tylko dziedziczenie pojedyncze (każdy obiekt ma tylko jeden prototyp), podczas gdy niektóre języki obsługują wielodziedziczenie.

Dobre praktyki przy pracy z prototypami

  1. Zrozumienie mechanizmu - ważne jest zrozumienie, jak działa łańcuch prototypów, aby skutecznie korzystać z dziedziczenia.
  2. Korzystanie z klas (ES6+) - dla większości przypadków użycia składnia klas jest bardziej czytelna i łatwiejsza w utrzymaniu.
  3. Unikanie modyfikacji wbudowanych prototypów - modyfikacja prototypów wbudowanych obiektów (np. Object.prototype, Array.prototype) może prowadzić do nieoczekiwanych konfliktów.
  4. Stosowanie Object.create() dla dziedziczenia - przy używaniu tradycyjnego podejścia, Object.create() jest czystym sposobem implementacji dziedziczenia prototypowego.
  5. Kompozycja nad dziedziczeniem - czasami lepiej jest używać kompozycji (łączenia obiektów) zamiast głębokiego dziedziczenia, aby uniknąć problemów z hierarchią.

Podsumowanie

Prototypy i dziedziczenie prototypowe są fundamentalnymi koncepcjami w JavaScript. Nawet gdy używamy nowoczesnej składni klas (ES6+), ważne jest zrozumienie leżącego u podstaw mechanizmu prototypów, aby w pełni wykorzystać możliwości języka. W naszym Parku Jurajskim dziedziczenie prototypowe pomaga nam modelować różne typy dinozaurów i ich zachowań w spójny, wydajny sposób.

Główne koncepcje, które omawialiśmy, to:

  1. Prototypy - mechanizm, dzięki któremu obiekty mogą dziedziczyć właściwości i metody od innych obiektów.
  2. Łańcuch prototypów - sekwencja obiektów połączonych przez ich prototypy, którą JavaScript przeszukuje, gdy próbuje uzyskać dostęp do właściwości.
  3. Funkcje konstruktora i prototypy - tradycyjny sposób implementacji dziedziczenia w JavaScript.
  4. Klasy ES6+ - nowoczesna składnia dla dziedziczenia, oparta na mechanizmie prototypów.
  5. Mixiny - sposób na łączenie funkcjonalności z różnych źródeł.

Zrozumienie prototypów i dziedziczenia w JavaScript jest kluczem do pisania efektywnego, dobrze zorganizowanego kodu, który może modelować złożone relacje między obiektami, takie jak te w naszym wirtualnym Parku Jurajskim.

Kod do tej lekcji: index.js
// Prototypy i dziedziczenie - Park Jurajski
console.log("Prototypy i Dziedziczenie");
console.log("Zaawansowane koncepcje OOP w JavaScript\n");

// ===========================================
// 1. PODSTAWY PROTOTYPÓW
// ===========================================
console.log("=== 1. Czym są prototypy? ===");

function Dinosaur(name, species) {
  this.name = name;
  this.species = species;
}

// Dodanie metody do prototypu
Dinosaur.prototype.roar = function() {
  return `${this.name} says: ROAARRR!`;
};

Dinosaur.prototype.getInfo = function() {
  return `${this.name} (${this.species})`;
};

const trex = new Dinosaur("Rexy", "T-Rex");
const raptor = new Dinosaur("Blue", "Velociraptor");

console.log("\n", trex.getInfo());
console.log("   ", trex.roar());
console.log("\n", raptor.getInfo());
console.log("   ", raptor.roar());

// Sprawdzenie prototypu
console.log("\nSprawdzenie prototypu:");
console.log(`   trex.__proto__ === Dinosaur.prototype: ${trex.__proto__ === Dinosaur.prototype}`);
console.log(`   raptor.constructor === Dinosaur: ${raptor.constructor === Dinosaur}`);

// ===========================================
// 2. ŁAŃCUCH PROTOTYPÓW
// ===========================================
console.log("\n=== 2. Łańcuch prototypów (Prototype Chain) ===");

console.log("\nŁańcuch prototypów dla trex:");
console.log(`   trex → Dinosaur.prototype → Object.prototype → null`);

console.log("\nMetody dostępne przez łańcuch:");
console.log(`   trex.getInfo() (z Dinosaur.prototype): ${trex.getInfo()}`);
console.log(`   trex.toString() (z Object.prototype): ${trex.toString()}`);
console.log(`   trex.hasOwnProperty('name'): ${trex.hasOwnProperty('name')}`);

// Sprawdzanie w łańcuchu
console.log("\ninstanceof:");
console.log(`   trex instanceof Dinosaur: ${trex instanceof Dinosaur}`);
console.log(`   trex instanceof Object: ${trex instanceof Object}`);

// ===========================================
// 3. DZIEDZICZENIE PROTOTYPOWE
// ===========================================
console.log("\n=== 3. Dziedziczenie prototypowe ===");

function Animal(name, age) {
  this.name = name;
  this.age = age;
}

Animal.prototype.breathe = function() {
  return `${this.name} oddycha`;
};

Animal.prototype.getAge = function() {
  return `${this.name} ma ${this.age} lat`;
};

// Carnivore dziedziczy po Animal
function Carnivore(name, age, huntingSkill) {
  Animal.call(this, name, age); // Wywołanie konstruktora rodzica
  this.huntingSkill = huntingSkill;
}

// Ustawienie dziedziczenia
Carnivore.prototype = Object.create(Animal.prototype);
Carnivore.prototype.constructor = Carnivore;

// Dodanie własnych metod
Carnivore.prototype.hunt = function() {
  return `${this.name} poluje (skill: ${this.huntingSkill}/10)`;
};

Carnivore.prototype.roar = function() {
  return `${this.name} ryczy: ROAARRR!`;
};

const rex = new Carnivore("Rex", 8, 10);

console.log("\nCarnivore (dziedziczy po Animal):");
console.log(`   ${rex.getAge()}`); // Z Animal
console.log(`   ${rex.breathe()}`); // Z Animal
console.log(`   ${rex.hunt()}`); // Własna metoda
console.log(`   ${rex.roar()}`); // Własna metoda

// ===========================================
// 4. KLASY ES6 (SYNTACTIC SUGAR)
// ===========================================
console.log("\n=== 4. Klasy ES6 ===");

class DinoBase {
  constructor(name, species, age) {
    this.name = name;
    this.species = species;
    this.age = age;
  }

  getInfo() {
    return `${this.name} (${this.species}) - ${this.age} lat`;
  }

  breathe() {
    return `${this.name} oddycha`;
  }
}

class CarnivoreClass extends DinoBase {
  constructor(name, species, age, huntingSkill) {
    super(name, species, age);
    this.huntingSkill = huntingSkill;
    this.type = "Mięsożerca";
  }

  hunt() {
    return `${this.name} poluje (skill: ${this.huntingSkill}/10)`;
  }

  roar() {
    return `${this.name} ryczy: ROAARRR!`;
  }

  // Nadpisanie metody z klasy bazowej
  getInfo() {
    return `${super.getInfo()} | Typ: ${this.type}`;
  }
}

class HerbivoreClass extends DinoBase {
  constructor(name, species, age, plantPreference) {
    super(name, species, age);
    this.plantPreference = plantPreference;
    this.type = "Roślinożerca";
  }

  eat() {
    return `${this.name} je ${this.plantPreference}`;
  }

  graze() {
    return `${this.name} spokojnie się pasie`;
  }

  getInfo() {
    return `${super.getInfo()} | Typ: ${this.type}`;
  }
}

const rexy = new CarnivoreClass("Rexy", "T-Rex", 8, 10);
const trike = new HerbivoreClass("Trike", "Triceratops", 7, "paprocie");

console.log("\nMięsożerca:");
console.log(`   ${rexy.getInfo()}`);
console.log(`   ${rexy.breathe()}`);
console.log(`   ${rexy.hunt()}`);
console.log(`   ${rexy.roar()}`);

console.log("\nRoślinożerca:");
console.log(`   ${trike.getInfo()}`);
console.log(`   ${trike.breathe()}`);
console.log(`   ${trike.eat()}`);
console.log(`   ${trike.graze()}`);

// ===========================================
// 5. WIELOPOZIOMOWE DZIEDZICZENIE
// ===========================================
console.log("\n=== 5. Wielopoziomowe dziedziczenie ===");

class LivingBeing {
  constructor(name) {
    this.name = name;
  }

  live() {
    return `${this.name} żyje`;
  }
}

class Reptile extends LivingBeing {
  constructor(name, scaleType) {
    super(name);
    this.scaleType = scaleType;
  }

  shedSkin() {
    return `${this.name} zrzuca skórę`;
  }
}

class PrehistoricReptile extends Reptile {
  constructor(name, scaleType, period) {
    super(name, scaleType);
    this.period = period;
    this.extinct = true;
  }

  getHistory() {
    return `${this.name} żył w okresie ${this.period}`;
  }
}

const velociraptor = new PrehistoricReptile("Blue", "małe", "Kredowy");

console.log("\nVelociraptor (3 poziomy dziedziczenia):");
console.log(`   ${velociraptor.live()}`); // Z LivingBeing
console.log(`   ${velociraptor.shedSkin()}`); // Z Reptile
console.log(`   ${velociraptor.getHistory()}`); // Z PrehistoricReptile

console.log("\ninstanceof (wielopoziomowe):");
console.log(`   instanceof PrehistoricReptile: ${velociraptor instanceof PrehistoricReptile}`);
console.log(`   instanceof Reptile: ${velociraptor instanceof Reptile}`);
console.log(`   instanceof LivingBeing: ${velociraptor instanceof LivingBeing}`);
console.log(`   instanceof Object: ${velociraptor instanceof Object}`);

// ===========================================
// 6. MIXINY (COMPOSITION OVER INHERITANCE)
// ===========================================
console.log("\n=== 6. Mixiny - kompozycja zamiast dziedziczenia ===");

// Mixin dla możliwości latania
const FlyingMixin = {
  fly() {
    return `${this.name} leci z prędkością ${this.flyingSpeed} km/h`;
  },
  land() {
    return `${this.name} ląduje`;
  }
};

// Mixin dla możliwości pływania
const SwimmingMixin = {
  swim() {
    return `${this.name} pływa`;
  },
  dive() {
    return `${this.name} nurkuje`;
  }
};

// Funkcja pomocnicza do dodawania mixinów
function addMixins(targetClass, ...mixins) {
  mixins.forEach(mixin => {
    Object.assign(targetClass.prototype, mixin);
  });
}

class Pteranodon {
  constructor(name, flyingSpeed) {
    this.name = name;
    this.flyingSpeed = flyingSpeed;
  }

  roar() {
    return `${this.name} krzyczy: SCREECH!`;
  }
}

class Mosasaurus {
  constructor(name) {
    this.name = name;
  }

  roar() {
    return `${this.name} ryczy pod wodą: ROAARRR!`;
  }
}

// Dodanie mixinów
addMixins(Pteranodon, FlyingMixin);
addMixins(Mosasaurus, SwimmingMixin);

const ptero = new Pteranodon("Pterry", 80);
const mosa = new Mosasaurus("Mosa");

console.log("\nPteranodon (z mixinem latania):");
console.log(`   ${ptero.roar()}`);
console.log(`   ${ptero.fly()}`);
console.log(`   ${ptero.land()}`);

console.log("\nMosasaurus (z mixinem pływania):");
console.log(`   ${mosa.roar()}`);
console.log(`   ${mosa.swim()}`);
console.log(`   ${mosa.dive()}`);

// ===========================================
// 7. PRZYKŁAD KOMPLEKSOWY
// ===========================================
console.log("\n=== 7. System ekosystemu - przykład kompleksowy ===");

class Ecosystem {
  constructor(name) {
    this.name = name;
    this.creatures = [];
  }

  addCreature(creature) {
    this.creatures.push(creature);
    console.log(`Dodano ${creature.name} do ekosystemu ${this.name}`);
  }

  simulate() {
    console.log(`\n============================================================`);
    console.log(`SYMULACJA EKOSYSTEMU: ${this.name}`);
    console.log("=".repeat(60));

    console.log(`\nŁącznie stworzeń: ${this.creatures.length}`);

    const carnivores = this.creatures.filter(c => c.type === "Mięsożerca");
    const herbivores = this.creatures.filter(c => c.type === "Roślinożerca");

    console.log(`   Mięsożercy: ${carnivores.length}`);
    console.log(`   Roślinożercy: ${herbivores.length}`);

    console.log("\nAktywności stworzeń:");
    this.creatures.forEach((creature, i) => {
      console.log(`\n  ${i + 1}. ${creature.getInfo()}`);
      console.log(`     ${creature.breathe()}`);

      if (creature.hunt) {
        console.log(`     ${creature.hunt()}`);
        console.log(`     ${creature.roar()}`);
      }

      if (creature.eat) {
        console.log(`     ${creature.eat()}`);
        console.log(`     ${creature.graze()}`);
      }
    });

    this.showFoodChain();
  }

  showFoodChain() {
    console.log("\nŁańcuch pokarmowy:");

    const carnivores = this.creatures.filter(c => c.type === "Mięsożerca");
    const herbivores = this.creatures.filter(c => c.type === "Roślinożerca");

    console.log(`   Rośliny → Roślinożercy (${herbivores.map(h => h.name).join(", ")})`);
    console.log(`   Roślinożercy → Mięsożercy (${carnivores.map(c => c.name).join(", ")})`);
  }
}

// Utworzenie ekosystemu
const jurassicEcosystem = new Ecosystem("Park Jurajski");

// Dodanie stworzeń
jurassicEcosystem.addCreature(new CarnivoreClass("Rexy", "T-Rex", 8, 10));
jurassicEcosystem.addCreature(new CarnivoreClass("Blue", "Velociraptor", 5, 9));
jurassicEcosystem.addCreature(new HerbivoreClass("Trike", "Triceratops", 7, "paprocie"));
jurassicEcosystem.addCreature(new HerbivoreClass("Stego", "Stegosaurus", 6, "rośliny"));
jurassicEcosystem.addCreature(new CarnivoreClass("Delta", "Velociraptor", 5, 8));

// Uruchom symulację
jurassicEcosystem.simulate();

console.log("\nGratulacje! Opanowałeś prototypy i dziedziczenie!");

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. 1. Co się dzieje, gdy próbujemy uzyskać dostęp do właściwości, której obiekt nie posiada?

  2. 2. Co robi metoda Object.create(proto)?

Zadania praktyczne w grze

  • Układanie w pionie

    Uporządkuj kroki szukania właściwości w łańcuchu prototypów:

  1. PytanieŁańcuch prototypów
  2. PytanieObject.create()
  3. Ułóż w kolejnościŁańcuch prototypów - kolejność szukania

Przydatne artykuły