zhuheyang
10/1/2017 - 7:36 AM

定义多个属性,Object.defineProperties(object,{}); 取得给定属性的描述符(descriptor),Object.getOwnPropertiyDescriptor().

定义多个属性,Object.defineProperties(object,{}); 取得给定属性的描述符(descriptor),Object.getOwnPropertiyDescriptor().

  var descriptor = Object.getPropertyDescriptor(book, "_year");
  console.log(descriptor.value);  //2004
  console.log(descriptor.configurable);  //false
  console.log(typeof descriptor.get);  //"undefined"

  var descriptor = Object.getPropertyDescriptor(book, "year");
  console.log(descriptor.value); //undefined
  console.log(descriptor.enumerable); //false
  console.log(typeof descriptor.get); //"function"
var book = {};
Object.defineProperties(book, function(){
   _year: {
     value: 2004
   },
     
   edition: {
     value: 1
   },
     
   year: {
     get: function(){
       return this._year;
     },
       
     set: function(newValue){
       if(newValue > 2004){
         this._year = newValue;
         this.edition += newValue - 2004;
       }
     }
   }
});