I have error when try to define property with accessors. Here is my code
var person = {}; Object.defineProperty(person, 'birthYear', { value: 1997, writable: true, enumerable: true, configurable: false, set: function (value) { this.birthYear = value; }, get: function() { return 'Birth year - ' + this.birthYear; } }); console.log(person.birthYear);
The error text:
Invalid property descriptor. Cannot both specify accessors and a value
or writable attribute.
If i can't define set and get methods like this how i can do it?
Best Answer
Look at the error message:
It doesn't make sense to say if a property is writable when you explicitly state what happens when you try to write it.
So remove:
And you can't give it a value, when the value is calculated dynamically when you read it, so remove:
Then you'll get an error about recursion because every time you try to read
person.birthYear
, your getter function tries to readperson.birthYear
.So store the value somewhere else.