js之oop <四>对象管理

对象扩展管理

Object.isExtensible() 检测对象是否可扩展(一般返回true)。
Object.preventExtensions() 防止对象扩展。

var p = {p1:"a",p1:"b"};
Object.isExtensible(p);     //返回true
Object.preventExtensions(p);    //防止对象扩展
Object.isExtensible(p);     //返回false

对象可扩展情况下,则可以添加属性。若不可扩展,则不能添加属性。

var p = {p1:"a",p1:"b"};
p.p3 = "new_element";
p.p3;   //输出new_element
Object.preventExtensions(p);    //防止对象扩展  
p.p4 = "new_extensible";    //添加属性失败
p.p4;   //输出undefined

但防止扩展,对象原有属性的属性标签仍都是true。

var p = {p1:"a",p1:"b"};
Object.preventExtensions(p);
Object.getOwnPropertyDescriptor(p,"p1");
//返回 { value: 'b', writable: true,  enumerable: true,  configurable: true }

这意味着原有属性可被删除,修改。

var p = {p1:"a",p1:"b"};
Object.preventExtensions(p);
delete p.p1;        //返回true 且p.p1输出undefined

***************************************************************************************************************

对象密封管理

Object.isSealed() 检测对象是否密封(一般返回false)。
Object.seal() 密封对象。

var o = { o1:1,o2:2 };
Object.seal(o); //密封对象
o.o3 = 3;       //赋值不成功 o.o3返回undefined
o.o1 = 81;      //o.o1返回81 修改成功
delete o.o1;    //返回false 删除不成功
Object.getOwnPropertyDescriptor(o,"o1");
//返回{ value: 1,writable: true,enumerable: true,configurable: false } 

对象设置seal后,对象除了禁止扩展,且对象所有属性的configurable都为false。

***************************************************************************************************************

对象冻结管理

Object.isFrozen() 检测对象是否冻结(一般返回false)。
Object.Freeze() 冻结对象。

var q = { q1:1,q2:2 };
Object.freeze(q);   //冻结对象
q.q3 = 3;           //赋值不成功 o.o3返回undefined
q.q2 = 100;         //q.q2返回2  修改失败
delete q.q2;        //返回false 删除不成功
Object.getOwnPropertyDescriptor(q,"q2");
//返回{ value: 2,writable: false,enumerable: true,configurable: false }

对象设置freeze后,对象除了被密封,且对象所有属性的writable属性都为false。

原文地址:https://www.cnblogs.com/MirageFox/p/5863355.html