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)
{
value: "Davron",
writable: true,
enumerable: true,
configurable: true
}
Bu har bir xususiyatning ichki tuzilishidir.
๐ 2-misol. Custom Descriptor'lar bilan xususiyat yaratishl
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"
- Agar true bo'lsa โ
for...inyokiObject.keys()looplarda ko'rinadi - Agar false bo'lsa โ loop lardan yashirin
const user = {};
Object.defineProperty(user, "name", {
value: "Davron",
enumerable: false
});
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
{
brand: { value: "BMW", writable: true, enumerable: true, configurable: true },
year: { value: 2020, writable: true, enumerable: true, configurable: true }
}