初级函子的作用非常简单,使用场景主要体现在:深入访问object的属性的时候,不会担心由于属性不存在、undefined、null等问题出现异常。
MayBe.js
var MayBe = function (val) { this.value = val; } MayBe.of = function (val) { return new MayBe(val); } MayBe.prototype.isNothing = function () { return (this.value === null || this.value === undefined); } MayBe.prototype.map = function (fn) { return this.isNothing() ? MayBe.of(null) : MayBe.of(fn(this.value)); } // demo1: MayBe?{value: "Mr. GOOGLE"} MayBe.of(‘Google‘) .map(_ => _.toUpperCase()) .map(_ => "Mr. " + _) // demo2: MayBe?{value: null} MayBe.of(‘Google‘) .map(_ => undefined) .map(_ => "Mr. " + _)
原文地址:https://www.cnblogs.com/CyLee/p/9318433.html
时间: 2024-10-10 16:34:42