13

I am trying to create an object with setters and getters, and this is my code:

var Player = function(height){
    var _height = height;

    Object.defineProperty(this, 'height', {
      enumerable: false
    , configurable: true
    , writable: false
    , get: function(){return _height;}
    , set: function(val){_height = val;}
    });
}

var myPlayer = new Player(10);

Even though the writable property of the defineProperty options is set to false, I get the following error:

Invalid property. A property cannot both have accessors and be writable or have a value, #<Object>

The same is happening when the writable is set to true of course, but the error disappears if I remove the writable line.

Am I doing something wrong, or is this a bug? This is happening on Google Chrome, Version 30.0.1599.66

Loupax
  • 4,728
  • 6
  • 41
  • 68
  • 1
    Error seems descriptive... Why would you have a getter and setter for a non-writable property? – elclanrs Oct 13 '13 at 19:29
  • 1
    The error is getting displayed in both cases, `writable: true` and `writable: false`. Isn't this weird? – Loupax Oct 13 '13 at 19:44
  • 1
    You can only either have the attributes `writable` and `value` or `get` and `set`, not any mixture of them. Since you specify `writable` , you cannot use `get` or `set`. See [Mozilla MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) – Ingo Bürk Oct 13 '13 at 19:46
  • 1
    Oh, it makes sense then. This comment should be an answer so I can accept it – Loupax Oct 13 '13 at 19:47

1 Answers1

35

The Mozilla MDN for Object.defineProperty clarifies this:

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

This means, that you can use either one of those:

  • writable and value
  • get and set

But you cannot use any combination of them. In your example, you specify the writable attribute, which means that it is a data descriptor, which disallows get and set attributes.

Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100