JavaScript 中的高阶函数(中)

123 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第14天,点击查看活动详情

如何创建 Polyfill

我们知道 JavaScript 为我们提供了一些内置的高阶函数,例如,map()等等。我们可以重新创建我们自己的这些功能的实现吗?让我们再深入一点。filter()``reduce()

我们已经在上一节中创建了过滤功能。让我们为filterFunction函数创建一个数组原型,以便我们可以将它与任何数组一起使用。这看起来像这样:

Array.prototype.filterFunction = function (callback) {
  const filteredArr = [];
  for (let i = 0; i < this.length; i++) {
    callback(this[i]) ? filteredArr.push(this[i]) : null;
  }
  return filteredArr;
};

在上面的代码中,this指的是调用原型的数组。因此,如果我们编写如下内容:

const arr = [1, 2, 3, 4, 5]
arr.filterFunction(callbackFn)

然后this将引用数组arr

现在我们可以filterFunction像使用filter()JS 中的内置函数一样使用了。我们可以这样写:

arr.filterFunction(isEven)

这类似于调用内置filter()函数:

arr.filter(isEven)

上述两个函数调用(即arr.filterFunction(isEven)and arr.filter(isEven))都会给我们相同的输出,比如[ 2, 4, 6, 8, 10 ].

同样,我们也可以在原型实现中传递箭头函数,就像我们可以传递内置filter()函数一样。

// I
arr.filterFunction((x) => x % 2 != 0)
arr.filter((x) => x % 2 != 0)
// both give the same output on console.log: [ 1, 3, 5, 7, 9, 11 ]

// II
arr.filterFunction((x) => x > 5)
arr.filter((x) => x > 5)
// both give the same output on console.log: [ 6, 7, 8, 9, 10, 11 ]

在某种程度上,我们为内置filter()函数编写了一个 polyfill。

函数链

我们也可以像使用内置filter()函数一样使用原型实现来实现函数链。让我们首先过滤掉所有大于 5 的数字。然后从结果中,我们将过滤掉所有偶数。它看起来像这样:

// Using our own filterFunction() prototype implementation
arr.filterFunction((x) => x > 5).filterFunction((x) => x % 2 === 0)

//Using the inbuilt filter() implementation
arr.filter((x) => x > 5).filter((x) => x % 2 === 0)

// both give the same output on console.log: [ 6, 8, 10 ]

这就是我们如何在 JS 中使用高阶函数来编写模式模块化、更简洁、更易于维护的代码。

未完待续