参考资料:
1.函数图解(SICP-1.2.6 )
2.https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976
3.https://medium.com/@jamesjefferyuk/javascript-what-are-pure-functions-4d4d5392d49c
纯函数(Pure functions):
Functions have some input (their arguments) and return some output (the result of applying them).
具有一些输入(参数)以及返回一些输出(调用结果)的函数。
- Given the same input, will always return the same output.
- Produces no side effects.
1 | Math.abs(-2) |
可以描述为接受输入并产生输出的小型机器
使用纯函数的好处:
One of the major benefits of using pure functions is they are immediately testable. They will always produce the same result if you pass in the same arguments.
非纯函数(Non-pure functions):
In addition to returning a value, applying a non-pure function can generate side effects, which make some change to the state of the interpreter or computer. A common side effect is to generate additional output beyond the return value, using the print function.
除了返回一个值之外,调用非纯函数会产生副作用,这会改变解释器或计算机的 一些状态。一个普遍的副作用就是在返回值之外生成额外的输出
Side effects include, but are not limited to:
- Making a HTTP request
- Mutating data
- Printing to a screen or console
- DOM Query/Manipulation
- Math.random()
- Getting the current time
1 | Math.random() |
调用console.log的嵌套表达式,会凸显出它的非纯特性
签名(Signatures):
A description of the arguments that a function can take is called the function’s signature.
函数的可接受参数的描述叫做函数的签名。
Math.abs(number) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs console.log(...) https://developer.mozilla.org/zh-CN/docs/Web/API/Console/log
借助抽象,不关系底层的具体计算过程,在根高层次shanghai思考问题; 函数是最基本的一种代码抽象方式