JavaScript’dagi har bir xossa (property) “yashirin” atributlarga ega:
for...in, Object.keys, JSON.stringify va Object.assign) ko‘rinsinmi?Oddiy tayinlash (masalan obj.a = 1) orqali yaratilgan xossalarning uchalasi ham default true bo‘ladi.
Object.defineProperty orqali berilsa, ko‘rsatilmagan bayroqlar default false deb olinadi.
Eslatma: Descriptor’lar ikki turga bo‘linadi:
- Data descriptor:
{ value, writable, enumerable, configurable }- Accessor descriptor:
{ get, set, enumerable, configurable }(undavalue/writablebo‘lmaydi)
Object.getOwnPropertyDescriptorconst user = { name: 'Ali' };
console.log(Object.getOwnPropertyDescriptor(user, 'name'));
/*
{
value: 'Ali',
writable: true,
enumerable: true,
configurable: true
}
*/
Barcha xossalarning descriptor’ini birdan ko‘rish:
console.log(Object.getOwnPropertyDescriptors(user));
Object.defineProperty / Object.definePropertiesconst obj = {};
Object.defineProperty(obj, 'id', {
value: 1001,
writable: false, // o‘zgartirib bo‘lmaydi
enumerable: false, // looplarda ko‘rinmaydi
configurable: false // o‘chirib/descriptorni o‘zgartirib bo‘lmaydi
});
console.log(obj.id); // 1001
obj.id = 2000; // strict bo‘lmasa — jim, strict’da TypeError
console.log(Object.keys(obj)); // [] — enumerable:false bo‘lgani uchun ko‘rinmaydi
Bir nechta xossani birvarakayiga:
Object.defineProperties(obj, {
createdAt: { value: Date.now(), writable: false, enumerable: true, configurable: false },
note: { value: 'readonly', writable: false, enumerable: true, configurable: true }
});
configurable: false bo‘lsa:
delete obj.prop ishlamaydi),enumerable va configurable o‘zgarmaydi,writable true → false ga o‘zgartirilishi mumkin, lekin false → true mumkin emas,writable: true bo‘lsa o‘zgaradi (aks holda o‘zgarmaydi).enumerable: false bo‘lsa, xossa for...in, Object.keys, JSON.stringify, Object.assign da ko‘rinmaydi; ammo Object.getOwnPropertyNames va Reflect.ownKeys uni ko‘rsatadi.