[javascript ECMAScript5 メモ] get,set

A.
EMCAScript5では、ゲッター、セッターが追加されました。
以下のような書式で記述します。
// Object Literal
console.log("Object Literal ---");
var obj = { _id: 1,
            get id() {
              return this._id;
            },
            set id(value) {
          if( isNaN(value) ) throw new Error("Not Number");
              this._id = value;
            }
          };
console.log( obj.id );
obj.id = 2;
console.log( obj.id );
console.log( Object.keys( obj ) );


// Object.defineProperty
console.log("Object.defineProperty ---");
var obj2 = {
  _id: 1
}

Object.defineProperty(obj2, "id", {
  enumerable: false,
  configurable: false,
  get : function(){
          return this._id;
        },
  set : function(value){
      if( isNaN(value) ) throw new Error("Not Number");
          this._id = value;
        }
});
console.log( obj2.id );
obj2.id = 2;
console.log( obj2.id );
console.log( Object.keys( obj2 ) );

// Private
console.log("Private ---");
var obj3 = {};
(function () {
  var _id = 1;
  Object.defineProperty(obj3, "id", {
    enumerable: false,
    configurable: false,
    get : function(){
            return _id;
          },
    set : function(value){
      if( isNaN(value) ) throw new Error("Not Number");
            _id = value;
          }
  });

})();
console.log( obj3.id );
obj3.id = 2;
console.log( obj3.id );
console.log( Object.keys( obj3 ) );
js_e5_sg1.png

参考サイト
MDN get
MDN set
ECMA-262 ECMA-262-5 in detail. Chapter 1. Properties and Property Descriptors.