Khóa property của object
Set giá trị một object trong js, chúng ta chỉ cần biết đến property: value
Vậy nếu muốn khóa property này không cho phép chỉnh sửa thì sao?
Mỗi property trong object sẽ được khuyến mãi thêm 3 flag attribute đặc biệt - descriptor
let user = {
name: "John"
};
let descriptor = Object.getOwnPropertyDescriptor(user, 'name');
console.log(JSON.stringify(descriptor, null, 2));
// kết quả
{
"value": "John",
"writable": true,
"enumerable": true,
"configurable": true
}- writable: =
truethì chúng ta cập nhập đượcvalue - enumerable: =
truethì khi loop chúng ta sẽ thấy nó - configurable: =
truethì có thể delete được, các attributewritable,enumerablecó thể chỉnh sửa
Để thay đổi giá trị cho các attribute này, chúng ta thực hiện thông qua hàm Object.defineProperty(obj, propertyName, descriptor)
let user = {}
Object.defineProperty(user, "name", { value: "John",
writable: false, enumerable: false, configurable: false})
// không còn change giá trị của name được nữa
user.name = "Peter";
// Error: Cannot assign to read only property 'name'
// không còn thấy khi loop
for (let key in user) console.log(key)Ví dụ một property có attribute configurable=false
// tự động gán false hết cho các attribute
let descriptor = Object.getOwnPropertyDescriptor(Math, 'PI');
/*
{
"value": 3.141592653589793,
"writable": false,
"enumerable": false,
"configurable": false
}
*/
Math.PI = 3;
// Error, because it has writable: false
// ko thể thay đổi attribute writable nữa
Object.defineProperty(Math, "PI", { writable: true });
// Error, because of configurable: falseNếu chỉ set
configurable = falsethì vẫn thay đổi giá trị được, nó chỉ không cho thay đổi attribute và delete
let user = {
name: "John"
};
Object.defineProperty(user, "name", {
configurable: false
});
user.name = "Pete"; // vẫn được
delete user.name; // ErrorNếu muốn khai báo nhiều property cùng lúc, dùng Object.defineProperties()
Object.defineProperties(obj, {
prop1: descriptor1,
prop2: descriptor2
// ...
});
// Ví dụ
Object.defineProperties(user, {
name: { value: "John", writable: false },
surname: { value: "Smith", writable: false },
// ...
});Lấy tất cả descriptor, Object.getOwnDescriptors(obj)
let clone = Object.defineProperties({}, Object.getOwnPropertyDescriptors(obj));Khóa toàn bộ object
Để khóa hẳn một object, chúng ta có đến tận 3 phương thức
Object.preventExtension(obj)không cho thể các property mớiObject.seal(obj)không cho thêm/xóa các property,configurable: falseObject.freeze(obj)không cho thêm/xóa/thay đổi property,configurable: false, writable: false




Initializing...