JsProperty

  • 139
  • 0
  • Js
  • 2020-01-17

Object.defineProperty : 定義屬性、調整屬性特微 ( 值、可否寫入、可否刪除,可否列舉)

Object.defineProperty 淺層保護

Object.definePropertys 大量屬性

防止擴充 PreventExtensions、封裝 Seal、凍結 Freeze *淺層保護

屬性Enum與Prototype Relation

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

Object.defineProperty(物件、屬性(字串)、參數)

var test = {
a: 1,
b:'2',
c: [3]
}

Object.defineProperty(test,'a',{
    value : 2,            //值
    writable : true,     //可否寫入 預設true
    configurable: true, //可否刪除 預設true
    enumerable : true,  //可否列舉 預設true
} );

test.a= 3;                //可否寫入
delete test.c;            //可否刪除
for (var key in test)    //可否列舉
  console.log(key);

console.dir(test);

~~~~~~~~~~~~~~~~~~~~~~~

Object.defineProperty 淺層保護

Object.defineProperty(test,'d',{
    value : {},           //值
    writable : false,     //可否寫入 預設true
} );
test.d = a; //淺層保護無法變動傳
test.d.a = 123; //深層 可變動

~~~~~~~~~~~~~~~~~~~~~~~

Object.definePropertys 大量屬性

Object.definePropertys(object, { 屬性: 參數 })

ref : https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

防止擴充 PreventExtensions (防止增加屬性、可以修改、刪除屬性)

var test = {
a: 1,
b:'2',
c: {}
}

Object.preventExtensions(test); //防止擴充
console.log('Extension:' + Object.isExtensible(test)); //檢查是否擴充
console.log('Property:'  + Object.getOwnPropertyDescriptor(test,'c')); //檢查屬性的參數

test.d ='z'; //not work
test.a = 'z'; test.c.a = '123'; delete test.b; //is work

console.log(test);

~~~~~~~~~~~~~~~

封裝 Seal (物件屬性無法新增、刪除,無法配置特徵,可以調整屬性值)

var test = {
a: 1,
b:'2',
c: {}
}

Object.seal(test); //物件屬性無法新增、刪除,無法配置特徵,可以調整屬性值
console.log('Seal:' + Object.isSealed(test)); //檢查是否封裝
console.dir(Object.getOwnPropertyDescriptor(test,'a')); //檢查屬性的參數

test.d ='z'; delete test.b; //not work
test.a = 'z'; test.c.a = '123';  //is work

console.log(test);

~~~~~~~~~~~~~~~

凍結 Freeze

var test = {
a: 1,
b:'2',
c: {}
}

Object.freeze(test); //物件屬性無法新增、刪除,無法配置特徵、調整屬性值
console.log('Frozen:' + Object.isFrozen(test)); //檢查是否封裝
console.dir(Object.getOwnPropertyDescriptor(test,'a')); //檢查屬性的參數

test.a = 'z'; test.d ='z'; delete test.b; //not work
test.c.a = '123'; test = {}; //is work ,不凍結物件初始
console.log(test);

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

屬性Enum與Prototype Relation

自訂義的原型屬性特徵下的可否列舉為true,與實際Object下的可否列舉為false

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ref : https://developer.mozilla.org/zh-TW/docs/Glossary/property/JavaScript