JavaScript ๐Ÿ“œ
October 7

Object Property Descriptors

๐Ÿง  Har bir xususiyat (property) yashirin attribyutlarga ega.

In JavaScript, each property of an object has three internal characteristics called descriptors:

Javascriptda biror obyektning har bir xususiyati 3 ta ichki harakteristikaga ega. Ular descriptorlar deyiladi:

Default holatida biz obyekt yaratganimizda (masalan: {name = "Davron"}) barcha descriptorlar qiymati true ga teng bo'ladi.

1-misol. Normal xususiyat (property)

const user = { name: "Davron" };

console.log(Object.getOwnPropertyDescriptor(user, "name"));

Output

{ value: "Davron", writable: true, enumerable: true, configurable: true }

Bu har bir xususiyatning ichki tuzilishidir.

๐Ÿ›  2-misol. Custom Descriptor'lar bilan xususiyat yaratishl

Sintaksis:

Object.defineProperty(object, propertyName, descriptor)

Masalan:

const user = {};

Object.defineProperty(user, "name", { value: "Davron", writable: false, // cannot be changed enumerable: true, // visible in loops configurable: false // cannot be deleted or modified });

console.log(user.name); // Davron user.name = "Aziz"; // โŒ ignored (writable: false) console.log(user.name); // Davron

๐Ÿงฉ Har bir Descriptor izohi:

1) ๐Ÿ–Š๏ธ writable

  • Agar true bo'lsa โ†’ property qiymati o'zgartirilishi mumkin.
  • Agar false bo'lsa โ†’ property qiymati o'zgarmaydi.

const obj = {}; Object.defineProperty(obj, "name", { value: "Davron", writable: false });

obj.name = "Aziz"; // โŒ ignored console.log(obj.name); // "Davron"

2) ๐Ÿ” enumerable

  • Agar true bo'lsa โ†’ for...in yoki Object.keys() looplarda ko'rinadi
  • Agar false bo'lsa โ†’ loop lardan yashirin

const user = {}; Object.defineProperty(user, "name", { value: "Davron", enumerable: false });

console.log(Object.keys(user)); // []

name bor bo'lsa ham ,u enumerable emas โ€” yani yashirin. Loop da ko'rinmaydi

3) โš™๏ธ configurable

  • Agar true bo'lsa โ†’ xususiyat o'chirilishi yoki qayta tayinlanishi mumkin.
  • Agar false bo'lsaโ†’ o'chirib yoki o'zgartirilib bo'lmaydi

const user = {}; Object.defineProperty(user, "age", { value: 25, configurable: false });

delete user.age; // โŒ fails silently console.log(user.age); // 25

๐Ÿงฎ 3-misol. Descriptorlarni ko'rish

const car = { brand: "BMW", year: 2020 };

console.log(Object.getOwnPropertyDescriptors(car));

Output

{ brand: { value: "BMW", writable: true, enumerable: true, configurable: true }, year: { value: 2020, writable: true, enumerable: true, configurable: true } }