LEARNING JAVASCRIPT - Trang 333

const

betterCoefficients

=

new

Proxy

(

coefficients

, {

get

(

target

,

key

) {

return

target

[

key

]

||

0

;

},
});

As I write this, proxies are not supported in Babel. However, they

are supported in the current build of Firefox, and these code sam‐

ples can be tested there.

The first argument to the

Proxy

constructor is the target, or object that’s being prox‐

ied. The second argument is the handler, which specifies the actions to be intercepted.

In this case, we’re only intercepting property access, denoted by the

get

function (this

is distinct from a

get

property accessor: this will work for regular properties and get

accessors). The

get

function takes three arguments (we’re only using the first two):

the target, the property key (either a string or a symbol), and the receiver (the proxy

itself, or something that derives from it).
In this example, we simply check to see if the key is set on the target; if it’s not, we

return the value

0

. Go ahead and try it:

betterCoefficients

.

a

;

// 1

betterCoefficients

.

b

;

// 0

betterCoefficients

.

c

;

// 3

betterCoefficients

.

d

;

// 0

betterCoefficients

.

anything

;

// 0;

We’ve essentially created a proxy for our

coefficients

object that appears to have an

infinite number of properties (all set to

0

, except the ones we define)!

We could further modify our proxy to only proxy single lowercase letters:

const

betterCoefficients

=

new

Proxy

(

coefficients

, {

get

(

target

,

key

) {

if

(

!

/^[a-z]$/

.

test

(

key

))

return

target

[

key

];

return

target

[

key

]

||

0

;

},
});

Instead of doing our easy check to see if

target[key]

is truthy, we could return

0

if

it’s anything but a number…I’ll leave that as a reader’s exercise.
Similarly, we can intercept properties (or accessors) being set with the

set

handler.

Let’s consider an example where we have dangerous properties on an object. We want

to prevent these properties from being set, and the methods from being called,

without an extra step. The extra step we’ll use is a setter called

allowDangerousOpera

tions

, which you have to set to

true

before accessing dangerous functionality:

Proxies | 309

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.