LEARNING JAVASCRIPT - Trang 325

CHAPTER 21

Object Property Configuration and Proxies

Accessor Properties: Getters and Setters

There are two types of object properties: data properties and accessor properties. We’ve

already seen both, but the accessor properties have been hidden behind some ES6

syntactic sugar (we called them “dynamic properties” in

Chapter 9

).

We’re familiar with function properties (or methods); accessor properties are similar

except they have two functions—a getter and a setter—and when accessed, they act

more like a data property than a function.
Let’s review dynamic properties. Imagine you have a

User

class, with methods

setE

mail

and

getEmail

. We opted to use a “get” and “set” method instead of just having a

property called

email

because we want to prevent a user from getting an invalid email

address. Our class is very simple (for simplicity, we’ll treat any string with an at sign

as a valid email address):

const

USER_EMAIL

=

Symbol

();

class

User

{

setEmail

(

value

) {

if

(

!

/@/

.

test

(

value

))

throw

new

Error(

`invalid email:

${

value

}

`

);

this

[

USER_EMAIL

]

=

value

;

}

getEmail

() {

return

this

[

USER_EMAIL

];

}
}

In this example, the only thing that’s compelling us to use two methods (instead of a

property) is to prevent the

USER_EMAIL

property from receiving an invalid email

address. We’re using a symbol property here to discourage accidental direct access of

301

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.