LEARNING JAVASCRIPT - Trang 189

// note that we can use destructuring to make
// this iteration even more natural:

for

(

let

[

u

,

r

]

of

userRoles

.

entries

())

console.log(

`

${

u

.

name

}

:

${

r

}

`

);

// the entries() method is the default iterator for
// a Map, so you can shorten the previous example to:

for

(

let

[

u

,

r

]

of

userRoles

)

console.log(

`

${

u

.

name

}

:

${

r

}

`

);

If you need an array (instead of an iterable object), you can use the spread operator:

[

...

userRoles

.

values

()];

// [ "User", "User", "Admin" ]

To delete a single entry from a map, use the

delete()

method:

userRoles

.

delete

(

u2

);

userRoles

.

size

;

// 2

Lastly, if you want to remove all entries from a map, you can do so with the

clear()

method:

userRoles

.

clear

();

userRoles

.

size

;

// 0

Weak Maps

A

WeakMap

is identical to

Map

except:

• Its keys must be objects.
• Keys in a

WeakMap

can be garbage-collected.

• A

WeakMap

cannot be iterated or cleared.

Normally, JavaScript will keep an object in memory as long as there is a reference to it

somewhere. For example, if you have an object that is a key in a

Map

, JavaScript will

keep that object in memory as long as the

Map

is in existence. Not so with a

WeakMap

.

Because of this, a

WeakMap

can’t be iterated (there’s too much danger of the iteration

exposing an object that’s in the process of being garbage-collected).
Thanks to these properties of

WeakMap

, it can be used to store private keys in object

instances:

const

SecretHolder

=

(

function

() {

const

secrets

=

new

WeakMap

();

return

class

{

setSecret

(

secret

) {

secrets

.

set

(

this

,

secret

);

}

getSecret

() {

Weak Maps | 165