Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

纯函数 #16

Open
39Er opened this issue Jun 5, 2017 · 0 comments
Open

纯函数 #16

39Er opened this issue Jun 5, 2017 · 0 comments

Comments

@39Er
Copy link
Owner

39Er commented Jun 5, 2017

纯函数的定义

纯函数是指不依赖于且不改变它作用域之外的变量状态的函数。

纯函数的返回值只由它调用时的参数决定,它的执行不依赖于系统的状态(比如:何时、何处调用它)

使用纯函数的好处

最主要的好处是没有副作用。纯函数不会修改作用域之外的状态,做到这一点,代码就变得足够简单和清晰:当你调用一个纯函数,你只要关注它的返回值,而不用担心因为别处的问题导致错误。

纯函数是健壮的,改变执行次序不会对系统造成影响,因此纯函数的操作可以并行执行。

纯函数非常容易进行单元测试,因为不需要考虑上下文环境,只需要考虑输入和输出。

最后,尽可能使用纯函数让你的代码保持简单和灵活。

纯函数的应用

典型应用1: Redux中的Reducer设计原则就是必须为纯函数

只要传入参数相同,返回计算得到的下一个 state 就一定相同。没有特殊情况、没有副作用,没有 API 请求、没有变量修改,单纯执行计算。

典型应用2: React函数式无状态组件

优点

相比于 class 创建组件

  • 语法更简洁
  • 占内存更小(class 有 props context _context 等诸多属性),首次 render 的性能更好
  • 可以写成无副作用的纯函数
  • 可拓展性更强(函数的 compose,currying 等组合方式,比 class 的 extend/inherit 更灵活)

缺点

  • 无生命周期函数

一个组件就是一个函数,函数应该是谈不上生命周期的,但是组件却是有生命周期,stateless functions 没有生命周期。当然了,我们其实可以使用 高阶组件 去实现生命周期

  • 没有 this

在 stateless functions 中,this 是 undefined,所以是不能使用 this 变量。不过换个角度思考,this 是在运行时随时可以被修改或重新赋值,跟外界环境有着密切的联系,正是不使用this才会让组件变得更纯。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant