物件延伸:物件擴充的修改與調整


Posted by hoyi-23 on 2021-08-13

上篇連結: Object 物件屬性特徵


之前有談過 Object.defindProperty(),它可以針對 屬性特徵 來做調整。
這篇要來介紹另外三個物件語法,它們可以針對 物件本身 做調整。

var person = {
    a:1,
    b:2,
    c:{}
}

preventExtension 防止擴充(寫入)

語法:

  1. Object.preventExtension(Object) 針對物件本身(不是物件屬性),防止物件擴充
  2. Object.isExtensible(Object) 查看物件是否可被擴充
  3. Object.getOwnPropertyDescriptior(Object,'屬性') 取得物件內的屬性特徵
Object.preventExtension(person); 
console.log(Object.isExtensible(person)); // false 針對物件本身不可被擴充
console.log(Object.getOwnPropertyDescriptior(person,'a'))
//{value:1, writable:true,configutable: true,enumarable: true}
//可以看到它的寫入還是true,是因為防止擴充是針對物件本身,不會影響物件的屬性特徵
person.a = 'a'; // 物件的屬性特徵還是可以寫入
person.d = 'd'; // 不能針對物件寫入!!!
person.c.a = '可以寫入' //可以巢狀新增

seal 封裝

語法: Object.seal(Object)
透過Seal封裝的物件將無法新增、刪除和重新配置特徵。但是可以寫入!!
Seal加入preventExtensions的概念,針對物件無法寫入。

Object.seal(person); 
console.log(Object.isExtensible(person)); // False 使用seal會同時防止物件擴充
console.log(Object.issealable(person)); // True
console.log(Object.getOwnPropertyDescriptior(person,'a'))
//{value:1, writable:true,configutable: false,enumarable: true}
//無法刪除
person.a = 'a'; // 物件的屬性特徵還是可以寫入
person.d = 'd'; // 不能針對物件寫入!!!
person.c.a = '可以寫入' //可以巢狀新增

Freeze 凍結

Freeze加上seal的概念。
除了針對物件無法擴充、刪除,它也無法調整值。

Object.freeze(person)
var person = {
    a:1, //只凍結此處
    b:2,//只凍結此處
    c:{}//只凍結此處
} 

//可以整個重新賦值
person = {};

#preventExtensions #seal #freeze







Related Posts

What is Azure Release Pipeline

What is Azure Release Pipeline

Secure Apache Using Certbot with Let's Encrypt on Ubuntu 20.04

Secure Apache Using Certbot with Let's Encrypt on Ubuntu 20.04

[04] Renderless Component

[04] Renderless Component


Comments