LEARNING JAVASCRIPT - Trang 190

return

secrets

.

get

(

this

);

}
}
})();

Here we’ve put our

WeakMap

inside an IIFE, along with a class that uses it. Outside the

IIFE, we get a class that we call

SecretHolder

whose instances can store secrets. We

can only set a secret through the

setSecret

method, and only get the secret through

the

getSecret

method:

const

a

=

new

SecretHolder

();

const

b

=

new

SecretHolder

();

a

.

setSecret

(

'secret A'

);

b

.

setSecret

(

'secret B'

);

a

.

getSecret

();

// "secret A"

b

.

getSecret

();

// "secret B"

We could have used a regular

Map

, but then the secrets we tell instances of

SecretHolder

could never be garbage-collected!

Sets

A set is a collection of data where duplicates are not allowed (consistent with sets in

mathematics). Using our previous example, we may want to be able to assign a user to

multiple roles. For example, all users might have the

"User"

role, but administrators

have both the

"User"

and

"Admin"

role. However, it makes no logical sense for a user

to have the same role multiple times. A set is the ideal data structure for this case.
First, create a

Set

instance:

const

roles

=

new

Set

();

Now if we want to add a user role, we can do so with the

add()

method:

roles

.

add

(

"User"

);

// Set [ "User" ]

To make this user an administrator, call

add()

again:

roles

.

add

(

"Admin"

);

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

Like

Map

,

Set

has a

size

property:

roles

.

size

;

// 2

Here’s the beauty of sets: we don’t have to check to see if something is already in the

set before we add it. If we add something that’s already in the set, nothing happens:

roles

.

add

(

"User"

);

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

roles

.

size

;

// 2

166 | Chapter 10: Maps and Sets

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.