Mutable - MDN Web Docs Glossary: Definitions of Web-related terms 编辑
Mutable is a type of variable that can be changed. In JavaScript, only objects and arrays are mutable, not primitive values.
(You can make a variable name point to a new value, but the previous value is still held in memory. Hence the need for garbage collection.)
A mutable object is an object whose state can be modified after it is created.
Immutables are the objects whose state cannot be changed once the object is created.
Strings and Numbers are Immutable. Lets understand this with an example:
var immutableString = "Hello"; // In the above code, a new object with string value is created. immutableString = immutableString + "World"; // We are now appending "World" to the existing value.
On appending the "immutableString" with a string value, following events occur:
- Existing value of "immutableString" is retrieved
- "World" is appended to the existing value of "immutableString"
- The resultant value is then allocated to a new block of memory
- "immutableString" object now points to the newly created memory space
- Previously created memory space is now available for garbage collection.
Learn more
General knowledge
- Immutable object on Wikipedia
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论