Question 56
Question
How would you implement a custom getter/setter using Object.defineProperty()
or using proxies?
Answer
1. Object.defineProperty()
This approach is more straightforward but offers less flexibility than Proxies.
Explanation:
We use
Object.defineProperty
to define a new property calledvalue
onmyObject
.The
get
function is executed when you accessmyObject.value
.The
set
function is executed when you assign a new value usingmyObject.value = ...
.A private property
_value
is used internally to store the actual value.
2. Proxies (More Powerful)
Proxies offer greater control and flexibility over property access.
Explanation:
We create a
handler
object that defines the behavior for our proxy.The
get
andset
functions in the handler are called whenever a property is accessed or modified.We use
new Proxy({}, handler)
to create a proxy based on an empty object ({}
) and our custom handler.
Choosing Between Object.defineProperty()
and Proxies:
Object.defineProperty()
: Simpler for basic getter/setter implementations.Proxies: More powerful, allowing you to intercept any property operation (including delete, hasOwnProperty) and control how they behave. Great for complex scenarios like logging, validation, or modifying values before saving them.
Last updated