javascript プロパティ属性
環境 CentOS 7.0 JavaScript
今までJavaScriptはきちんと勉強せず感覚で使っていなあ、とよく思う今日この頃。
プロパティ属性
オブジェクトの持つプロパティには、以下の属性を設定できる。
名前 | 役割 |
---|---|
value | 値 |
writable | 書き込み可 |
enumerable | 列挙可 |
configurable | 再定義可 |
get | 取得 |
set | 設定 |
アクセッサである、get,setにも属性を設定できるが、writableは指定できない。
"use strict"; // 1プロパティずつ設定 p1 = {}; Object.defineProperty(p1, "x", { value : 1, writable: false, enumerable: false, configurable: false, get r(){return this.x;}, set r(newvalue){return this.x = newvalue;}, }); // まとめて設定2 var p2 = Object.defineProperties({}, { x: { value: 1, writable: true, enumerable:true, configurable:true }, y: { value: 1, writable: true, enumerable:false, configurable:false}, r: { get: function() { return this.x + this.y; }, set: function(newvalue) { this.x = newvalue; this.y = this.x * 2; }, enumerable:false, configurable:true } });
p1,p2のオブジェクトの私方が違うが、どちらのメソッドもどちらでも設定可能。
この状態で、writable = false, configuable = falseになっているところに変更をかけると、
p1.x = 2; // TypeError: Cannot assign to read only property 'x' of #<Object delete p1.x; // TypeError: Cannot delete property 'x' of #<Object
のようにTypeErrorが発生する(strictのときのみ)。
またenumerableは
console.log(Object.keys(p2)); // [ 'x' ]
のようにfalseだと列挙できなくなる。
get,setは説明不要と思うが、
console.log(p2.r); // 2 p2.r = 2; console.log(p2.r); // 6
となる。