Celaro
Celaro

Reputation: 226

JavaScript Object defineProperties not working

So I have learned that in Javascript we can use defineProperties to define multiple properties of object. I have therefore tried it in a simple code below but I am not quiet getting the result I wanted. It seems that the accessors is not working and I don't know why.

var book = {};
Object.defineProperties(book,{
 _year: {
    value: 2004 },
 edition: {
    value: 1},
 year: {
    get: function(){
    this._year;},
    set: function(value){
    if(value>2004){
     this._year = value;
     this.edition = this.edition + value - 2004;
 });
 this.year = 2016;
 alert(book.edition); //1 why??

Upvotes: 1

Views: 5370

Answers (1)

t.niese
t.niese

Reputation: 40842

You have multiple errors In your code, but the main problem is that, if you define a property with value then it is by default readonly:

MDN: Object.defineProperty

writable
true if and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.

You need to add writable: true to make those properties writable.

So your code has to look like this (including the correction for all other errors you had):

var book = {};
Object.defineProperties(book, {
  _year: {
    value: 2004,
    writable: true // << writable
  },
  edition: {
    value: 1,
    writable: true // << writable
  },
  year: {
    get: function() {
      // << missing return
      return this._year;
    },
    set: function(value) {

      if (value > 2004) {
        this._year = value;
        this.edition = this.edition + value - 2004;
      }
    }
  }
});
book.year = 2016; // << here you used this instead of book
console.log(book.edition);

Upvotes: 5

Related Questions