javascriptで getter setter

  • 普通にゲッターセッターを追加する場合
var o = {
    firstName: null,
    lastName:  null,

    get fullName() {
        return this.firstName+' '+this.lastName;
    },
    init: function(){
      this.firstName = 'Tarou';
      this.lastName  = 'Yamada';
      console.log(this.fullName);
      this.lastName  = 'Takeda';
      console.log(this.fullName);
    }
};
o.init();
Tarou yamada
  • prototypeに追加する場合
Object.defineProperty(o, "myProperty", {
    get: function myProperty() {
        // code
    }
});