We can control property attributes with
Object.defineProperty
, which allows you
to create new properties or modify existing ones (as long as the property is configura‐
ble).
For example, if we want to make the
foo
property of
obj
read-only, we can use
Object.defineProperty
:
Object
.
defineProperty
(
obj
,
'foo'
, {
writable
:
false
});
Now if we try to assign a value to
foo
, we get an error:
obj
.
foo
=
3
;
// TypeError: Cannot assign to read only property 'foo' of [object Object]
Attempting to set a read-only property will only result in an error
in strict mode. In nonstrict mode, the assignment will not be suc‐
cessful, but there will be no error.
We can also use
Object.defineProperty
to add a new property to an object. This is
especially useful for attribute properties because, unlike with data properties, there’s
no other way to add an accessor property after an object has been created. Let’s add a
color
property to
o
(we won’t bother with symbols or validation this time):
Object
.
defineProperty
(
obj
,
'color'
, {
get
:
function
() {
return
this
.
color
; },
set
:
function
(
value
) {
this
.
color
=
value
; },
});
To create a data property, you provide the
value
property to
Object.defineProp
erty
. We’ll add
name
and
greet
properties to
obj
:
Object
.
defineProperty
(
obj
,
'name'
, {
value
:
'Cynthia'
,
});
Object
.
defineProperty
(
obj
,
'greet'
, {
value
:
function
() {
return
`Hello, my name is
${
this
.
name
}
!`
; }
});
One common use of
Object.defineProperty
is making properties not enumerable
in an array. We’ve mentioned before that it’s not wise to use string or symbol proper‐
ties in an array (because it is contrary to the use of an array), but it can be useful if
done carefully and thoughtfully. While the use of
for...in
or
Object.keys
on an
array is also discouraged (instead prefer
for
,
for...of
, or
Array.prototype.forE
ach
), you can’t prevent people from doing it. Therefore, if you add non-numeric
properties to an array, you should make them non-enumerable in case someone
(inadvisably) uses
for..in
or
Object.keys
on an array. Here’s an example of adding
sum
and
avg
methods to an array:
304 | Chapter 21: Object Property Configuration and Proxies