应用纯函数有几个长处:
- 它们很轻易导出和调试,因为它们不依附于可变的状况。
- 返回值可以被缓存或者“记忆”来避免今后反复计算。
- 它们很轻易测试,因为没有须要模仿(mock)的依附(比如日记,AJAX,数据库等等)。
你编写或者应用的函数返回空(换句话说它没有返回值),那代表它长短纯函数。
不变性
让我们回到捕获变量的概念上。来看看 canRide 函数。我们认为它是一个非纯函数,因为 heightRequirement 变量可以被从新赋值。下面是一个构造出来的例子来解释若何用弗成猜测的值来对它从新赋值。
- let heightRequirement = 46;
- function canRide(height) {
- return height >= heightRequirement;
- }
- // Every half second, set heightRequirement to a random number between 0 and 200.
- setInterval(() => heightRequirement = Math.floor(Math.random() * 201), 500);
- const mySonsHeight = 47;
- // Every half second, check if my son can ride.
- // Sometimes it will be true and sometimes it will be false.
- setInterval(() => console.log(canRide(mySonsHeight)), 500);
我要再次强调被捕获的变量不必定会使函数成为非纯函数。我们可以经由过程只是简单地改变 heightRequirement 的声明方法来使 canRide 函数成为纯函数。
- const heightRequirement = 46;
- function canRide(height) {
- return height >= heightRequirement;
- }
经由过程用 const 来声明变量意味着它不克不及被再次赋值。如不雅测验测验对它从新赋值,运行时引擎将抛掉足误;那么,如不雅用对象来代替数字来存储所有的“常量”怎么样?
- const constants = {
- heightRequirement: 46,
- // ... other constants go here
- };
- function canRide(height) {
- return height >= constants.heightRequirement;
- }
我们用了 const ,所以这个变量不克不及被从新赋值,然则还有一个问题:这个对象可以被改变。下面的代码展示了,为了真正使其弗成变,你不仅须要防止它被从新赋值,你也须要弗成变的数据构造。JavaScript 说话供给了 Object.freeze 办法来阻拦对象被改变。
- 'use strict';
- // CASE 1: 对象的属性是可变的,并且变量可以被再次赋值。
- let o1 = { foo: 'bar' };
- // 改变对象的属性
- o1.foo = 'something different';
- // 对变量再次赋值
- o1 = { message: "I'm a completely new object" };
- // CASE 2: 对象的属性照样可变的,然则变量不克不及被再次赋值。
- const o2 = { foo: 'baz' };
- // 仍然能改变对象
推荐阅读
沙龙晃荡 | 去哪儿、陌陌、ThoughtWorks在主动化运维中的实践!10.28不见不散! 几周前,我们开端写一个系列,>>>详细阅读
地址:http://www.17bianji.com/lsqh/38230.html
1/2 1