1

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??
2
  • You seem to be missing several } Commented Oct 11, 2016 at 16:22
  • Yes, I just realized I was missing those closing brackets, the formatting style did not make it clear. Thanks Commented Oct 11, 2016 at 16:27

1 Answer 1

5

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, Indeed I just read about that fact when using defineProperties. Enumerable, configurable, and writable are false by default.
The return in the getter doesn't seem to be required
@j08691 It is indeed not relevant for the given code, but it would return undefined if the OP tries read the property year at another place in the code, so I added this correction as extra info. Because otherwise this getter would not make much sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.