Lodash/Underscore 语法相对于 vanilla JS 语法的组合优势

Compositional advantage of Lodash/Underscore syntax over vanilla JS syntax

我正在熟悉一些 Lodash/Underscore 方法并且有一个关于语法的基本问题。


如果我有一个用户对象列表,并且想按年龄小于 40 岁的用户过滤该列表,我可以编写以下香草 JavaScript:

// Vanilla JS
var result = users.filter((d) => d.age < 40);

LoDash/Underscore 提供了另一种语法来产生相同的结果:

// Lodash, Underscore
var result = _.filter(users, (d) => d.age < 40); 

这两个产生相同的结果和return一个数组。

使用后一种语法有什么组合优势(如果有的话)?为什么它比使用纯 JS 语法更可取?


编辑

因为我收到了像 "one requires an additional library and one doesn't" 和 "they execute different code" 这样的回答,所以我想澄清一下。

function composition 的角度来看,使用 lodash/underscore 方法比 Vanilla JS 方法有什么优势吗?

假设您有以下函数 compose

function compose(f, g) {
  return function apply(...args) {
    return g(f(...args));
  }
}

您可以使用它将两个函数组合在一起以创建一个函数。

const inc = x => x + 1;
const double = x => x * 2;

const doubleAndInc = compose(double, inc);
doubleAndInc(3) // 7
const incAndDouble = compose(inc, double);
incAndDouble(3) // 8

这些函数可以组合,因为它们只依赖于它们的参数。 Lodash的filter函数也是如此。

const filterFirst = compose(_.filter, _.head);
filterFirst([1, 2, 3], x => x % 2 == 0); // 2

Array.prototype.filter 不使用数组作为参数调用。相反,它使用其内部 this 值——通常是调用该方法的数组。

compose 函数对 this 一无所知。它仅适用于参数和 return 值,这意味着它不能用于组合依赖 this 而不仅仅是参数的函数。