LEARNING JAVASCRIPT - Trang 329

const

arr

=

[

3

,

1.5

,

9

,

2

,

5.2

];

arr

.

sum

=

function

() {

return

this

.

reduce

((

a

,

x

)

=>

a

+

x

); }

arr

.

avg

=

function

() {

return

this

.

sum

()

/

this

.

length

; }

Object

.

defineProperty

(

arr

,

'sum'

, {

enumerable

:

false

});

Object

.

defineProperty

(

arr

,

'avg'

, {

enumerable

:

false

});

We could also do this in one step per property:

const

arr

=

[

3

,

1.5

,

9

,

2

,

5.2

];

Object

.

defineProperty

(

arr

,

'sum'

, {

value

:

function

() {

return

this

.

reduce

((

a

,

x

)

=>

a

+

x

); },

enumerable

:

false

});

Object

.

defineProperty

(

arr

,

'avg'

, {

value

:

function

() {

return

this

.

sum

()

/

this

.

length

; },

enumerable

:

false

});

Lastly, there is also a

Object.defineProperties

(note the plural) that takes an object

that maps property names to property definitions. So we can rewrite the previous

example as:

const

arr

=

[

3

,

1.5

,

9

,

2

,

5.2

];

Object

.

defineProperties

(

arr

,

sum

:

{

value

:

function

() {

return

this

.

reduce

((

a

,

x

)

=>

a

+

x

); },

enumerable

:

false

}),

avg

:

{

value

:

function

() {

return

this

.

sum

()

/

this

.

length

; },

enumerable

:

false

})
);

Protecting Objects: Freezing, Sealing, and Preventing

Extension

JavaScript’s flexible nature is very powerful, but it can get you into trouble. Because

any code anywhere can normally modify an object in any way it wishes, it’s easy to

write code that is unintentionally dangerous or—even worse—intentionally mali‐

cious.
JavaScript does provide three mechanisms for preventing unintentional modifications

(and making intentional ones more difficult): freezing, sealing, and preventing exten‐

sion.
Freezing prevents any changes to an object. Once you freeze an object, you cannot:

• Set the value of properties on the object.
• Call methods that modify the value of properties on the object.

Protecting Objects: Freezing, Sealing, and Preventing Extension | 305

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.