Object.defineProperty () vs Object.prototype.property vs Object.property, when to use which?
Suppose we have an object person
with a property age
with a value 20
.
The Object.defineProperty () method defines a new property directly on an object, or modifies an existing property on an object and returns an object.
Object.defineProperty(obj, prop, descriptor)
How is this different from the normal assignment operator?
This gives you more control over property creation than the standard assignment ( person.age = 25
). In addition to setting the value, you can specify whether the property can be deleted or edited, among other things, as detailed here on the Object.defineProperty () page .
A few examples
To add a name field to this face that cannot be changed using an assignment operator:
Object.defineProperty(person, "name", {value: "Jim", writable: false})
or update the age property and make it editable:
Object.defineProperty(person, "age", {value: 25, writable: true})
...
Object.prototype.property and Object.property refer to object accessor. This is similar to accessing a property of an age
object person
with person.age
(you can also use person["age"]
)
source to share