Can somebody give me a good use case of when to use Object.defineProperty(), Object.prototype.property and Object.property.
-
1What exactly do you mean by "`Object.prototype.property`"? There is no such property. Are you asking "*when to use the prototype?*" or "*when to put a property on `Object.prototype`*" or "*What's the difference between putting properties on the prototype and on the constructor?*"? – Bergi Aug 04 '15 at 19:39
-
1You might be looking for [Why is it Object.defineProperty() rather than this.defineProperty()?](http://stackoverflow.com/q/13239317/1048572) or [Object.defineProperty vs vanilla property](http://stackoverflow.com/q/29861269/1048572) regarding `defineProperty`. – Bergi Aug 04 '15 at 19:43
-
Possible duplicate of [Object.defineProperty or .prototype?](https://stackoverflow.com/questions/38961414/object-defineproperty-or-prototype) – Michael Freidgeim Oct 02 '19 at 07:44
1 Answers
Imagine we have a person
object with an age
property with a value of 20
.
The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
Object.defineProperty(obj, prop, descriptor)
How is this different than the normal assignment operator?
It gives you more control over creating a property than standard assignment (person.age = 25
). On top of setting the value, you can specify whether a property can be deleted or edited among other things outlined in more detail here Object.defineProperty() page.
A few examples
To add an name field to this person that cannot be changed with an assignment operator:
Object.defineProperty(person, "name", {value: "Jim", writable: false})
or to update the age property and make it editable:
Object.defineProperty(person, "age", {value: 25, writable: true})
.
Object.prototype.property and Object.property both refer to accessing a property of an object. This is like accessing the age
property of the person
object using person.age
(you can also use person["age"]
)

- 668
- 1
- 6
- 17
-
-
1
-
It gives you more control over creating a property than the standard person.age = 25. On top of setting the value, you can specify whether a property can be deleted or edited among other things. – Mike G Aug 04 '15 at 19:50
-
2Yeah, please put that in your answer, that's what the OP wants to know :-) – Bergi Aug 04 '15 at 19:58