# JavaScript klasslar (class, constructor)

> JavaScript klasslari: class e'loni, constructor, metodlar, getter va setter, static hamda maxfiy xossalar. Obyektlarni shablondan yaratishni o'rganing.

Manba: https://learncode.uz/javascript/klasslar/
Sana: 2026-06-03

Bitta [obyekt](https://learncode.uz/javascript/obyektlar) yaratish oson. Ammo yuzta bir xil
tuzilishdagi obyekt kerak bo'lsa — har birini qo'lda yozish mumkin emas.
**Klass** shu obyektlar uchun shablon beradi.

## Muammo: takrorlanadigan obyektlar

```js
const t1 = { name: "Aziz", score: 85, state() { return this.score >= 60; } };
const t2 = { name: "Dilnoza", score: 92, state() { return this.score >= 60; } };
```

Tuzilma bir xil, metod har obyektda qayta yozilgan. Shablon kerak.

## Birinchi klass

```js
class Student {
  constructor(name, score) {
    this.name = name;
    this.score = score;
  }

  hasPassed() {
    return this.score >= 60;
  }

  describe() {
    return this.name + " — " + this.score + " ball";
  }
}

const aziz = new Student("Aziz", 85);
const dilnoza = new Student("Dilnoza", 45);

console.log(aziz.describe());
console.log(aziz.hasPassed());
console.log(dilnoza.hasPassed());
```

> **Atama**
>
> **Klass** — obyektlar uchun shablon. **`new`** kalit so'zi shablondan yangi
> nusxa (**obyekt** yoki **instance**) yaratadi. **`constructor`** — `new`
> paytida avtomatik chaqiriladigan maxsus metod; u boshlang'ich xossalarni
> o'rnatadi.

## new nima qiladi

`new Student("Aziz", 85)` uch qadamni bajaradi:

1. bo'sh obyekt yaratadi;
2. uni `this` qilib `constructor` ni chaqiradi;
3. shu obyektni qaytaradi.

`new` ni unutish — keng uchraydigan xato:

```js
class Student {
  constructor(name) {
    this.name = name;
  }
}

try {
  const t = Student("Aziz");
} catch (error) {
  console.log("Xato:", error.message);
}
```

## Metodlar umumiy saqlanadi

```js
class Student {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return "Salom, " + this.name;
  }
}

const a = new Student("Aziz");
const b = new Student("Dilnoza");

console.log(a.greet());
console.log(a.greet === b.greet);
```

`true` chiqdi — metod har obyektda nusxalanmaydi, bitta joyda saqlanadi.
Xotira tejaladi. Bu mexanizm [prototip](https://learncode.uz/javascript/prototip) darsida
ochiladi.

## Standart qiymat va tekshiruv

```js
class Product {
  constructor(title, price, count = 1) {
    if (price < 0) {
      throw new Error("Narx manfiy bo'lolmaydi");
    }
    this.title = title;
    this.price = price;
    this.count = count;
  }

  total() {
    return this.price * this.count;
  }
}

const apple = new Product("Olma", 12000, 3);
console.log(apple.total());

const bread = new Product("Non", 5000);
console.log(bread.count, bread.total());

try {
  new Product("Xato", -100);
} catch (e) {
  console.log(e.message);
}
```

Constructor — ma'lumot to'g'riligini tekshirish uchun eng mos joy.

## Getter va setter

Xossa kabi ko'rinadigan, lekin funksiya bo'lgan a'zolar:

```js
class Circle {
  constructor(radius) {
    this.radius = radius;
  }

  get area() {
    return +(Math.PI * this.radius ** 2).toFixed(2);
  }

  get diameter() {
    return this.radius * 2;
  }

  set diameter(value) {
    this.radius = value / 2;
  }
}

const a = new Circle(5);

console.log(a.area);
console.log(a.diameter);

a.diameter = 20;
console.log(a.radius);
```

`a.area` — qavssiz chaqirilyapti, lekin har safar qaytadan hisoblanadi.
`set` esa o'zlashtirishni ushlab, boshqa xossani yangiladi.

## Maxfiy xossalar

`#` bilan boshlangan xossaga tashqaridan tegib bo'lmaydi:

```js
class Account {
  #balance = 0;

  constructor(initial) {
    this.#balance = initial;
  }

  add(amount) {
    if (amount <= 0) return "Noto'g'ri amount";
    this.#balance += amount;
    return this.#balance;
  }

  get balance() {
    return this.#balance;
  }
}

const h = new Account(1000);
console.log(h.add(500));
console.log(h.add(-50));
console.log(h.balance);
console.log(Object.keys(h));
```

`Object.keys` maxfiy xossani ko'rsatmadi — `#balans` faqat klass ichida
mavjud. Tashqarida `h.#balans` deb yozish esa umuman **sintaksis xatosi**:
kod ishga ham tushmaydi.

Bu [closure](https://learncode.uz/javascript/scope-closure) bilan erishilgan yopiqlikning
klassdagi rasmiy shakli.

## static — klassning o'zida

```js
class MathUtils {
  static PI = 3.14159;

  static square(n) {
    return n * n;
  }

  static average(...numbers) {
    return numbers.reduce((a, b) => a + b, 0) / numbers.length;
  }
}

console.log(MathUtils.PI);
console.log(MathUtils.square(7));
console.log(MathUtils.average(10, 20, 30));
```

`static` a'zolar **klassga** tegishli, obyektga emas — `new` shart emas.
Ko'pincha yordamchi funksiyalar va sanoqlar uchun ishlatiladi.

## Amaliy mashq

1. `Book` klassini yozing: `title`, `author`, `year`;
2. `describe()` metodini qo'shing;
3. constructor'da `year` ni tekshiring — kelajakdagi sana bo'lsa xato bering;
4. `get age` getter qo'shing (hozirgi yildan ayirsin);
5. `#copies` maxfiy xossasi va uni oshiruvchi metod yozing;
6. `static compare(a, b)` bilan ikki kitobni yil bo'yicha solishtiring.

## Qisqacha xulosa

- **Klass** — obyektlar uchun shablon; `new` bilan nusxa yaratiladi.
- `constructor` boshlang'ich xossalarni o'rnatadi va tekshiruv uchun mos joy.
- Metodlar barcha nusxalar uchun **bitta joyda** saqlanadi.
- `get`/`set` xossa ko'rinishidagi funksiyalar beradi.
- `#` maxfiy xossa — tashqaridan murojaat qilib bo'lmaydi.
- `static` a'zolar klassning o'ziga tegishli.

Keyingi darsda [meros](https://learncode.uz/javascript/meros) — klasslarni kengaytirish.
