最近在看函数式编程指南看到容器的部分有点看不懂,其中有一段代码讲Functor的如下:class Maybe { static of(x) { console.log(1); return new Maybe(x); } get isNothing() { console.log(2); return this.$value === null || this.$value === undefined; } constructor(x) { console.log(3); this.$value = x; } map(fn) { console.log(4); return this.isNothing ? this : Maybe.of(fn(this.$value)); } inspect() { console.log(5); return this.isNothing ? 'Nothing' : `Just(${this.$value})`; }}var test1 = Maybe.of('Malkovich Malkovich');console.log(test1);var test2 = Maybe.of(null).map(_.match(/a/ig));console.log(test2);var test3 = Maybe.of({ name: 'Boris' }) .map(_.prop('age')) .map(_.add(10));console.log(test3);var test4 = Maybe.of({ name: 'Boris', age: 14 }) .map(_.prop('age')) .map(_.add(10));console.log(test4);比较奇怪和不理解的是inspect函数是怎么执行的?似乎没有地方调用这个函数呀。希望有大神可以解答交流一下~
添加回答
举报
0/150
提交
取消