我不明白为什么我得到这个" bmDup不是一个功能"错误,而信息告诉我,我需要检索一个可能 如果我将它包装在一个函数中,则返回undefined。
function Maybe () {
Object.freeze(this);
};
function Just (x) {
this.toString = function () { return "Just " + x.toString(); };
this.just = x;
Object.freeze(this);
};
Just.prototype = new Maybe();
Just.prototype.constructor = Just;
function Nothing () {
this.toString = function () { return "Nothing"; };
Object.freeze(this);
};
Nothing.prototype = new Maybe();
Nothing.prototype.constructor = Nothing;
Maybe.unit = function (x) {
// return a Maybe that holds x
return new Just (x);
};
Maybe.bind = function (f) {
// given a function from a value to a Maybe return a function from a Maybe to a Maybe
return new Maybe(f(this.just));
};
//to test
function mDup(str) {
return new Just(str+str);
}
console.log(mDup("abc")); // => new Just("abcabc") OK
var bmDup = Maybe.bind(mDup);
console.log(bmDup(new Just("abc"))) // => new Just("abcabc") NOK

答案 0 :(得分:1)
首先,让我们看一下Maybe.bind
实际做了什么。
Maybe.bind = function (f) {
// Construct a new Maybe object, passing in the result of f(this.just)
return new Maybe(f(this.just));
};
好的,那么什么是Maybe
对象?
function Maybe () {
Object.freeze(this);
};
嗯,它是一个冻结的物体。所以Maybe.bind
返回一个对象,而不是一个函数。