编写一个将二元函数作为方法的函数

Write a function that takes a binary function to a method

我发现该解决方案存在编码问题,但没有解释该解决方案为何有效。我希望有人能帮助我了解解决方案的工作原理。

A binary function is a function that takes two inputs and returns a value, like for example add(3,5) -> 8. Write a function named "methodification", that converts a binary function to a method. For example:

function add (a, b) {return a + b;}
Number.prototype.add = methodification(add);
(3).add(5) === 8; // true

这是解决方案:

function methodification (func) {
  return function (b) {
    return func(this, b); 
  };
}

这个解决方案背后的逻辑是什么?

首先要说的是,在现实生活中没有人会编写这样的代码,但这是函数式编程如何在 JS 中工作的一个很好的例子。解释:

Number.prototype.add = function(b) { return this + b; }

就是你想要的最终结果。由于 3 具有原型 Number,您可以在句法上像对待对象一样对待它并在其上调用方法,在这些方法中 3 === 这是正确的。知道这一点你可以推断 methodification(add) 一定是上面这行代码的右边,所以它一定是一个函数,因此 methodification 一定是一个以函数为参数的函数,在本例中是“add”,和 returns 另一个函数,所以 methodification 是所谓的高阶函数。所以现在你可以“作弊”并做

function methodification(func) {
    return function(b) {
       return this + b;
    }
}

简单地返回右侧并忽略参数 func,但是因为 this + b === add(this, b) 你可以按照解决方案所说的去做。就是这样,不需要魔法。