Table 21-1. Object protection options
Action
Normal object Frozen object Sealed object Nonextensible object
Add property
Allowed
Prevented
Prevented
Prevented
Read property
Allowed
Allowed
Allowed
Allowed
Set property value
Allowed
Prevented
Allowed
Allowed
Reconfigure property
Allowed
Prevented
Prevented
Allowed
Delete property
Allowed
Prevented
Prevented
Allowed
Proxies
New in ES6 are proxies, which provide additional metaprogramming functionality
(metaprogramming is the ability for a program to modify itself).
An object proxy essentially has the ability to intercept and (optionally) modify
actions on an object. Let’s start with a simple example: modifying property access.
We’ll start with a regular object that has a couple of properties:
const
coefficients
=
{
a
:
1
,
b
:
2
,
c
:
5
,
};
Imagine that the properties in this object represent the coefficients in a mathematical
equation. We might use it like this:
function
evaluate
(
x
,
c
) {
return
c
.
a
+
c
.
b
*
x
+
c
.
c
*
Math
.
pow
(
x
,
2
);
}
So far, so good…we can now store the coefficients of a quadratic equation in an
object and evaluate the equation for any value of
x
. What if we pass in an object with
missing coefficients, though?
const
coefficients
=
{
a
:
1
,
c
:
3
,
};
evaluate
(
5
,
coefficients
);
// NaN
We could solve the problem by setting
coefficients.b
to
0
, but proxies offer us a
better option. Because proxies can intercept actions against an object, we can make
sure that undefined properties return a value of
0
. Let’s create a proxy for our
coeffi
cients
object:
308 | Chapter 21: Object Property Configuration and Proxies