Programming Self-Study Notebook

勉強したことを忘れないように! 思い出せるように!!

JavaScriptの文法(オブジェクトの保護)

f:id:overworker:20200406080809j:plain:h250

オブジェクト保護のオプション一覧

操作 通常 フリージング シーリング 拡張不可
プロパティの追加 × × ×
プロパティの読み込み
プロパティの値の設定 ×
プロパティのディスクリプタの変更 × ×
プロパティの削除 × ×

Object.freeze

'use strict';
const appInfo = {
  company:'Freeze Test, Inc',
  versiom:'1.1.1',
  buildId:'1234567890',
  copyright(){
    return `© ${new Date().getFullYear()}, ${this.company}`;
  },
};

Object.freeze(appInfo);
console.log(Object.isFrozen(appInfo));

// プロパティの追加
// appInfo.address = 'test';
// Uncaught TypeError: Cannot add property address, object is not extensible

// プロパティの削除
// delete appInfo.company;
// Uncaught TypeError: Cannot delete property 'company' of #<Object>

// プロパティの更新
// appInfo.company = 'Freeze Test2, Inc';
// main.js:130 Uncaught TypeError: Cannot assign to read only property 'company' of object '#<Object>'

// ディスクリプタの変更
// Object.defineProperty(appInfo,'company',{enumerable:false});
// Uncaught TypeError: Cannot redefine property: company at Function.defineProperty (<anonymous>)

Object.seal

'use strict';
class Logger {
  constructor(name) {
    this.name = name;
    this.log = [];
  };
  add(entry){
    this.log.push({
      log:entry,
      timestamp: Date.now(),
    });
  }
};

const log = new Logger("船長の航海日誌");
Object.seal(log);
console.log(Object.isSealed(log));

log.name = "船長の退屈な航海日誌";

log.add("またまた退屈な日だ...");
 
// プロパティの追加
// log.newProp = 'test';
// Uncaught TypeError: Cannot add property newProp, object is not extensible

// プロパティの削除
// delete log.name
// Uncaught TypeError: Cannot delete property 'name' of #<Logger>

// プロパティの更新
log.name = '先生の業務日誌'

Object.preventExtensionsObject.isExtensible

'use strict';
class Logger {
  constructor(name) {
    this.name = name;
    this.log = [];
  };
  add(entry){
    this.log.push({
      log:entry,
      timestamp: Date.now(),
    });
  }
};

const log2 = new Logger("一等航海士の航海日誌");
Object.preventExtensions(log2);
console.log(Object.isExtensible(log2));
log2.name = "一等航海士の退屈な航海日誌";
log2.add("またまた退屈な日だ...");
console.log(log2);

// プロパティの追加
// log2.newProp = 'test';
// Uncaught TypeError: Cannot add property newProp, object is not extensible

// プロパティの更新
log2.name = '船長代理の航海日誌';

// 
delete log2.name;

// 
Object.defineProperty(log2,'log',{enumerable:false});
console.log(log2);

参考文献