Klasa jako komponent strony

Klasy i obiekty - JavaScript od podstaw: konsola (HTML/CSS/JS)

Klasa może budować kawałek strony. Konstruktor `Counter` tworzy elementy (pudełko, napis, wartość, przycisk), podpina je do rodzica i obsługuje kliknięcie. Każdy obiekt ma WŁASNY stan (`this.value`) i własne elementy, więc trzy liczniki z jednej klasy działają niezależnie. Funkcja strzałkowa w `addEventListener` zachowuje `this` obiektu, dlatego `this.increment()` trafia we właściwy licznik.

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>Liczniki</title>
  <style>
    body { font-family: sans-serif; max-width: 34em; }
    .counter { display: inline-flex; gap: 0.5em; align-items: center; border: 1px solid #94a3b8; border-radius: 6px; padding: 0.4em 0.7em; margin: 0.3em; }
    .counter .value { min-width: 2em; text-align: center; font-weight: bold; }
    button, input { font: inherit; padding: 0.2em 0.6em; }
    #list li { cursor: pointer; margin: 0.2em 0; }
    #list li.done { text-decoration: line-through; color: #64748b; }
  </style>
</head>
<body>
  <h1>Głosowanie</h1>
  <div id="app"></div>
  <script>
    class Counter {
      constructor(parent, label) {
        this.value = 0;
        this.box = document.createElement('div');
        this.box.className = 'counter';
        const name = document.createElement('span');
        name.textContent = label;
        this.output = document.createElement('span');
        this.output.className = 'value';
        const button = document.createElement('button');
        button.className = 'inc';
        button.textContent = '+1';
        button.addEventListener('click', () => this.increment());
        this.box.append(name, this.output, button);
        parent.appendChild(this.box);
        this.render();
      }

      increment() {
        this.value++;
        this.render();
      }

      render() {
        this.output.textContent = String(this.value);
      }
    }
    const app = document.getElementById('app');
    const counters = ['Pizza', 'Pierogi', 'Sushi'].map(label => new Counter(app, label));
    counters[1].increment();
  </script>
</body>
</html>

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu JavaScript od podstaw: konsola·Zaloguj się, aby zapisać postęp na koncie.