出现:
- MayBe函子的出现是为了解决当传递空值时导致函子无法创建的问题
- MayBe函子允许当传递空值时创建函子做出额外的控制
- MayBe函子对普通函子具有更严谨的优势,可以兼容出现传递空值时的情况
缺点:
- 当多次调用map方法时,回调函数返回空值时,无法准确判断异常出现的位置
```javascript
class MayBe {
static of (values) {
} constructor(value) {return new MayBe(values);
} map(fn) {this._vlaue = value;
} isNothings(){// return MayBe.of(fn(this._vlaue)) return this.isNothings() ? MayBe.of(null) : MayBe.of(fn(this._vlaue))
} }return this._vlaue === null || this._vlaue === undefined;
// 不为空值时 // const res = MayBe.of(‘hello world’).map(x => x.length) // console.log(res)
// 为空值时 // const res = MayBe.of(null).map(x => x.length); // console.log(res) // MayBe {_value: null}
// 多次调用map时 出现了无法明确知道是哪一次map出现了异常 const res = MayBe.of(‘hello world’).map(x => x.length).map(y => null).map(k => k.toUpperCase()) console.log(res) ```