蒙屿森
蒙屿森

Reputation: 21

How to use Object.defineProperties?

everyone, I read Professional.JavaScript.for.Web.Developers.3rd.Edition recently. Here's the code I learn from it. However, the output is different from the book I read. When I run the code below, book.edition is 1, book._year is 2004 and book.year is 2004. What happen?What's wrong with my code?

var book = {};

Object.defineProperties(book, {
  _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;
      }
    }
  }
});

book.year = 2005;
console.log(book.edition);
console.log(book._year);
console.log(book.year);

Upvotes: 1

Views: 38

Answers (1)

ffflabs
ffflabs

Reputation: 17481

Properties _year and edition of your object should be defined as writable. Otherwise it's useless to redefine them inside year's setter.

var book = {};

Object.defineProperties(book, {
  _year: {
    value: 2004,
    writable:true
  },
  edition: {
    value: 1,
    writable:true
  },

  year: {
    
    get: function() {
      return this._year;
    },

    set: function(newValue) {
      
      if (newValue > 2004) {
        this._year = newValue;
        this.edition += newValue - 2004;
      }
    }
  }
});


console.log(book.edition);
console.log(book.year);
book.year=2005;
console.log(book.edition);
console.log(book.year);

Upvotes: 3

Related Questions