Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong behaviour in Google Chrome Object.defineProperty?

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

like image 374
Loupax Avatar asked Oct 13 '13 19:10

Loupax


People also ask

What parameters does the function object defineProperty () accept?

Parameters. The object on which to define the property. The name or Symbol of the property to be defined or modified. The descriptor for the property being defined or modified.

Can we change the configurable attribute of an object property to true?

Modifying a property It is not possible to change any attribute of a non-configurable accessor property. For data properties, it is possible to modify the value if the property is writable, and it is possible to change writable attribute from true to false.

What is the syntax of object define property () method in Javascript?

Syntax: Object. defineProperty(obj, prop, descriptor)


1 Answers

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.

like image 52
Ingo Bürk Avatar answered Oct 06 '22 00:10

Ingo Bürk