const
cook
=
{
name
:
"Walt"
,
redPhosphorus
:
100
,
// dangerous
water
:
500
,
// safe
};
const
protectedCook
=
new
Proxy
(
cook
, {
set
(
target
,
key
,
value
) {
if
(
key
===
'redPhosphorus'
) {
if
(
target
.
allowDangerousOperations
)
return
target
.
redPhosphorus
=
value
;
else
return
console
.
log
(
"Too dangerous!"
);
}
// all other properties are safe
target
[
key
]
=
value
;
},
});
protectedCook
.
water
=
550
;
// 550
protectedCook
.
redPhosphorus
=
150
;
// Too dangerous!
protectedCook
.
allowDangerousOperations
=
true
;
protectedCook
.
redPhosphorus
=
150
;
// 150
This only scratches the surface of what you can do with proxies. To learn more, I rec‐
ommend starting with Axel Rauschmayer’s article
.
Conclusion
In this chapter, we’ve pulled back the curtain that hides JavaScript’s object mechanism
and gotten a detailed picture of how object properties work, and how we can recon‐
figure that behavior. We also learned how to protect objects from modification.
Lastly, we learned about an extremely useful new concept in ES6: proxies. Proxies
allow powerful metaprogramming techniques, and I suspect we will be seeing some
very interesting uses for proxies as ES6 gains popularity.
310 | Chapter 21: Object Property Configuration and Proxies