1. 设置 configurable: false; writable: false 后,属性会不可删除不可修改,但可以新增属性
**2. Object.**preventExtensions() 可以让对象不可新增属性
var obj = {a: 2};
Object.preventExtensions(obj)
obj.b = 3;
console.log(obj);
Object.isExtensible() 是否可拓展
var obj = {a: 2};
var obj2 = {a: 2};
Object.preventExtensions(obj)
console.log(Object.isExtensible(obj));
console.log(Object.isExtensible(obj2));
使用 Object.defineProperty() 添加的属性,属性描述符默认是 false
var obj = {a: 2};
obj.c = 8;
Object.defineProperty(obj, 'b', {
value: 6
})
console.log(Object.getOwnPropertyDescriptor(obj, 'b'));
console.log(Object.getOwnPropertyDescriptor(obj, 'c'));
3. Object.seal() 使对象密封, Object.isSealed() 对象是否密封
var obj = {a: 2};
Object.seal(obj);
obj.b = 3;
console.log(Object.isSealed(obj));
console.log(obj);
4. Object.freeze() 冻结对象
var obj = {a: 2};
Object.freeze(obj);
console.log(Object.isFrozen(obj));
⭐️ 封装深层冻结对象
function myFreeze(obj) {
Object.freeze(obj);
for (var key in obj) {
if (typeof(obj[key]) === 'object' && obj[key] !== null) {
myFreeze(obj[key]);
}
}
}
var obj = {
a: {
b: {
c: 123
}
}
}
myFreeze(obj);
obj.a.b.d = 345;
console.log(obj);
is 比较运算的扩充