Property flags and descriptors
Property flags
屬性除了值還有 3 個標誌,創造屬性時不會看到他們,因為預設皆為 true。
writable– iftrue, can be changed, otherwise it’s read-only.enumerable– iftrue, then listed in loops, otherwise not listed.configurable– iftrue, the property can be deleted and these attributes can be modified, otherwise not.
// Object.getOwnPropertyDescriptor() 可以完整取得屬性的資訊
let descriptor = Object.getOwnPropertyDescriptor(obj, propertyName);
let user = {
name: "John"
};
let descriptor = Object.getOwnPropertyDescriptor(user, 'name');
alert( JSON.stringify(descriptor, null, 2 ) );
/* property descriptor:
{
"value": "John",
"writable": true,
"enumerable": true,
"configurable": true
}
*/
// Object.defineProperty() 可以改變屬性的標誌
Object.defineProperty(obj, propertyName, descriptor)
// 屬性存在會改變標誌,屬性不存在會創造,但標誌皆為 false
let user = {};
Object.defineProperty(user, "name", {
value: "John"
});
let descriptor = Object.getOwnPropertyDescriptor(user, 'name');
alert( JSON.stringify(descriptor, null, 2 ) );
/*
{
"value": "John",
"writable": false,
"enumerable": false,
"configurable": false
}
*/Read-only
Non-enumerable
Non-configurable
Object.defineProperties
Object.getOwnPropertyDescriptors
Last updated
Was this helpful?