[Javascript] Avoiding Mutations in JavaScript with Immutable Data Structures
JavaScript in with Data Immutable
2023-09-14 09:00:49 时间
To demonstrate the difference between mutability and immutability, imagine taking a drink from a glass of water. If our glass is mutable, when we take a drink, we retain the same glass and change the amount of water in that glass. However, if our glass is immutable, when we take a drink, we get back a brand new, identical glass containing the correctly drank amount. Perhaps a strange way to conceive of the action, but creating new data structures makes our methods pure and thread-safe, a benefit of functional programming.
class MutableGlass { constructor(content, amount) { this.content = content this.amount = amount } takeDrink(value) { this.amount = Math.max(this.amount - value, 0) return this } } // We can verify this by checking the references of the first glass and // the glass returned by `takeDrink()` and see that they are the same. const mg1 = new MutableGlass('water', 100) const mg2 = mg1.takeDrink(20) console.log(mg1.amount === 80 && mg1.amount === mg2.amount) // true console.log(mg1 === mg2) // true
Immutable class, whch every time should return a new instance:
// Taking a drink from the immutable glass returns an entirely new glass, // but with the correct content and amount of it in the glass. class ImmutableGlass { constructor(content, amount) { this.content = content this.amount = amount } takeDrink(value) { return new ImmutableGlass(this.content, Math.max(this.amount - value, 0)) } } // We can verify this by checking the references and seeing that they are // _not_ equal const ig1 = new ImmutableGlass('water', 100) const ig2 = ig1.takeDrink(20) console.log(ig1.amount !== ig2.amount) // true console.log(ig1 === ig2) // false
相关文章
- WebStorm Mac中文版(JavaScript开发工具)
- javascript html转换成markdown,如何使用Turndown使用JavaScript将HTML转换为Markdown[通俗易懂]
- javascript 空格_css怎样输出空格
- 用javascript分类刷leetcode19.数组(图文视频讲解)5
- JavaScript创建和使用命名空间详解编程语言
- JavaScript学习总结(十七)——Javascript原型链的原理详解编程语言
- in Neo4j查询:使用Not In操作(neo4j查询not)
- Oracle替代in:抛弃IN,开启新的查询方式(oracle代替in)
- MySQL中使用IN排序查询记录(mysql按in排序)
- 方法利用SQL Server中的IN方法提升数据查询效率(sqlserver的in)
- 借助MSSQL语句实现IN的强大功能(mssql语句 in)
- MySQL中IN的用法和意义(mysql中in的意思)
- MySQL中使用IN操作会影响性能吗(mysql中in性能)
- 探究MySQL中IN表达式的作用及实际应用(mysql中in作用)
- 中利用IN语句检索Oracle数据库中的数据(in在oracle数据库)
- MySQL不支持IN运算符如何解决(mysql 不支持in)
- Oracle IN查询双重优势一步搞定复杂任务(oracle两个in查询)
- 将光标定位到textarea的某一行的javascript代码
- [HTML/CSS/Javascript]WWTJS
- Javascript面向对象继承
- JavaScript高级程序设计客户端存储学习笔记
- javascript两种function的定义介绍及区别说明
- JavaScript如何从listbox里同时删除多个项目
- JavaScript中“过于”犀利地for/in循环使用示例
- JavaScript获取网页、浏览器、屏幕高度和宽度汇总
- JavaScript中的console.log()函数详细介绍