LEARNING JAVASCRIPT - Trang 331

}

add

(

entry

) {

this

.

log

.

push

({

log

:

entry

,

timestamp

:

Date

.

now

(),

});
}
}

const

log

=

new

Logger

(

"Captain's Log"

);

Object

.

seal

(

log

);

Object

.

isSealed

(

log

);

// true

log

.

name

=

"Captain's Boring Log"

;

// OK

log

.

add

(

"Another boring day at sea...."

);

// OK

log

.

newProp

=

'test'

;

// TypeError: Can't add property newProp, object is not extensible

log

.

name

=

'test'

;

// OK

delete

log

.

name

;

// TypeError: Cannot delete property 'name' of [object Object]

Object

.

defineProperty

(

log

,

'log'

, {

enumerable

:

false

});

// TypeError: Cannot redefine property: log

Finally, the weakest protection, making an object nonextensible, only prevents new

properties from being added. Properties can be assigned to, deleted, and reconfig‐

ured. Reusing our

Logger

class, we can demonstrate

Object.preventExtensions

and

Object.isExtensible

:

const

log2

=

new

Logger

(

"First Mate's Log"

);

Object

.

preventExtensions

(

log2

);

Object

.

isExtensible

(

log2

);

// true

log2

.

name

=

"First Mate's Boring Log"

;

// OK

log2

.

add

(

"Another boring day at sea...."

);

// OK

log2

.

newProp

=

'test'

;

// TypeError: Can't add property newProp, object is not extensible

log2

.

name

=

'test'

;

// OK

delete

log2

.

name

;

// OK

Object

.

defineProperty

(

log2

,

'log'

,

{

enumerable

:

false

});

// OK

I find that I don’t use

Object.preventExtensions

very often. If I want to prevent

extensions to an object, I typically also want to prevent deletions and reconfiguration,

so I usually prefer sealing an object.

Table 21-1

summarizes the protection options.

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

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.