LEARNING JAVASCRIPT - Trang 330

• Invoke setters on the object (that modify the value of properties on the object).
• Add new properties.
• Add new methods.
• Change the configuration of existing properties or methods.

In essence, freezing an object makes it immutable. It’s most useful for data-only

objects, as freezing an object with methods will render useless any methods that mod‐

ify the state of the object.
To freeze an object, use

Object.freeze

(you can tell if an object is frozen by calling

Object.isFrozen

). For example, imagine you have an object that you use to store

immutable information about your program (such as company, version, build ID, and

a method to get copyright information):

const

appInfo

=

{

company

:

'White Knight Software, Inc.'

,

version

:

'1.3.5'

,

buildId

:

'0a995448-ead4-4a8b-b050-9c9083279ea2'

,

// this function only accesses properties, so it won't be

// affected by freezing

copyright

() {

return

${

new

Date

().

getFullYear

()

}

,

${

this

.

company

}

`

;

},
};

Object

.

freeze

(

appInfo

);

Object

.

isFrozen

(

appInfo

);

// true

appInfo

.

newProp

=

'test'

;

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

delete

appInfo

.

company

;

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

appInfo

.

company

=

'test'

;

// TypeError: Cannot assign to read-only property 'company' of [object Object]

Object

.

defineProperty

(

appInfo

,

'company'

, {

enumerable

:

false

});

// TypeError: Cannot redefine property: company

Sealing an object prevents the addition of new properties, or the reconfiguration or

removal of existing properties. Sealing can be used when you have an instance of a

class, as methods that operate on the object’s properties will still work (as long as

they’re not attempting to reconfigure a property). You can seal an object with

Object.seal

, and tell if an object is sealed by calling

Object.isSealed

:

class

Logger

{

constructor

(

name

) {

this

.

name

=

name

;

this

.

log

=

[];

306 | 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.