オブジェクト保護のオプション一覧
操作 |
通常 |
フリージング |
シーリング |
拡張不可 |
プロパティの追加 |
〇 |
× |
× |
× |
プロパティの読み込み |
〇 |
〇 |
〇 |
〇 |
プロパティの値の設定 |
〇 |
× |
〇 |
〇 |
プロパティのディスクリプタの変更 |
〇 |
× |
× |
〇 |
プロパティの削除 |
〇 |
× |
× |
〇 |
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));
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.name = '先生の業務日誌'
Object.preventExtensions
とObject.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.name = '船長代理の航海日誌';
delete log2.name;
Object.defineProperty(log2,'log',{enumerable:false});
console.log(log2);
参考文献