- 函子可以把函数式编程中的副作用控制在可控范围内,如异常处理,异常操作等
- 什么是函子:
容器:包含值和值的变形关系(这个变形关系就是函数)
函子:是一个特殊的容器,通过一个普通的对象来实现,该对象具有map方法,map方法可以运行一个函数对值进行处理(变形关系)
// Functor 函子
class Container {
constructor (value) {
this._value = value
}
map (fn) {
return new Container(fn(this._value))
}
}
let r = new Container(5)
.map(x => x + 1)
.map(x => x * x)
console.log(r)
函子维护一个值value,但是这个值不对外公布,只能通过map方法接收一个处理值的函数,调用map方法,会返回一个新的函子,所以可以一直链式map操作;
为了符合函数式编程:函子中避免使用new的方法:
class Container {
static of (value) {
return new Container(value)
}
constructor (value) {
this._value = value
}
map (fn) {
return Container.of(fn(this._value))
}
}
let r = Container.of(5)
.map(x => x + 2)
.map(x => x * x)
console.log(r)
- 总结
- 函数式编程的运算不直接操作值,而是由函子完成
- 函子就是一个实现了map契约的对象
- 我们可以把函子想象成一个盒子,这个盒子里封装了一个值
- 想要处理盒子中的值,需要给盒子的map方法传递一个处理值的函数(纯函数),由这个函数来对值进行处理
- 最终map方法返回一个包含新值的盒子(函子)
// 演示 null undefined 的问题
Container.of(null)
.map(x => x.toUpperCase())//这个时候会报错