Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

immutability - Why would I need to freeze an object in JavaScript?

It is not clear to me when anyone would need to use Object.freeze in JavaScript. MDN and MSDN don't give real life examples when it is useful. I get that part about not being able to change it at runtime which is enforced by a crash. The question is rather when would I appreciate a crash.

To me the immutability is a design time constraint which is supposed to be guaranteed by the type checker.

So is there any point in having a runtime crash in a dynamically typed language, besides detecting a violation better later than never?

question from:https://stackoverflow.com/questions/14791302/why-would-i-need-to-freeze-an-object-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Object.freeze function does the following:

  • Makes the object non-extensible, so that new properties cannot be added to it.
  • Sets the configurable attribute to false for all properties of the object. When - configurable is false, the property attributes cannot be changed and the property cannot be deleted.
  • Sets the writable attribute to false for all data properties of the object. When writable is false, the data property value cannot be changed.

That's the what part, but why would anyone do this?

Well, in the object-oriented paradigm, the notion exists that an existing API contains certain elements that are not intended to be extended, modified, or re-used outside of their current context. The final keyword in various languages is the most suitable analogy of this. Even in languages that are not compiled and therefore easily modified, it still exists, i.e. PHP, and in this case, JavaScript.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...