I wanted to override the numberFruits property of the object fruits.

Tell me where is the error in the code?

enter image description here

var fruits = {}; Object.defineProperties(fruits, { "numberFruits": { value: 1, configuration: true }, "fruit": { get() { return this.numberFruits; }, set(value) { if(value >= 0 && value <=3) { Object.defineProperty(this, "numberFruits", { value: value }); } else { alert("Error!"); } }, enumerable: true } }); alert(fruits.fruit); fruits.fruit = 2; alert(fruits.fruit); 
  • You are in the setter trying to override the property again, but you just need to overwrite it. - Klimenkomud
  • What is the reason why this.numberFruits = {value} didn't this.numberFruits = {value} you? - vp_arth
  • @Klimenkomud, it is impossible to overwrite this property, and to be precise, to change its value using the assignment operator. Because when determining it, the data descriptor key writable received the value false . Therefore, changing the value of a property is possible only via defineProperty . If the error is removed from the code, of course. ) - Spomni

1 answer 1

Access descriptors and data do not have the configuration key, but are configurable .

In the sixth line, you, as I understand it, wanted to describe the numberFruits property as configurable, but used a non-existing key for this. And the correct key has become the default, which does not allow you to change the property in the future.

Replace the configuration in the sixth line with configurable , and you will be like that. )

PS Carefully read the documentation. I wish you success.