LEARNING JAVASCRIPT - Trang 326

the property (if we used a string property called

email

or even

_email

, it would be

easy to carelessly access it directly).
This is a common pattern, and it works well, but it’s slightly more unwieldy than we

might like. Here’s an example of using this class:

const

u

=

new

User

();

u

.

setEmail

(

"[email protected]"

);

console.log(

`User email:

${

u

.

getEmail

()

}

`

);

While this works, it would be more natural to write:

const

u

=

new

User

();

u

.

email

=

"[email protected]"

;

console.log(

`User email:

${

u

.

email

}

`

);

Enter accessor properties: they allow us to have the benefits of the former with the

natural syntax of the latter. Let’s rewrite our class using accessor properties:

const

USER_EMAIL

=

Symbol

();

class

User

{

set

email

(

value

) {

if

(

!

/@/

.

test

(

value

))

throw

new

Error(

`invalid email:

${

value

}

`

);

this

[

USER_EMAIL

]

=

value

;

}

get

email

() {

return

this

[

USER_EMAIL

];

}
}

We’ve provided two distinct functions, but they are bundled into a single property

called

email

. If the property is assigned to, then the setter is called (with the assign‐

ment value being passed in as the first argument), and if the property is evaluated, the

getter is called.
You can provide a getter without a setter; for example, consider a getter that provides

the perimeter of a rectangle:

class

Rectangle

{

constructor

(

width

,

height

) {

this

.

width

=

width

;

this

.

height

=

height

;

}

get

perimeter

() {

return

this

.

width

*

2

+

this

.

height

*

2

;

}
}

We don’t provide a setter for perimeter because there’s no obvious way to infer the

rectangle’s width and height from the length of the perimeter; it makes sense for this

to be a read-only property.

302 | Chapter 21: Object Property Configuration and Proxies

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.