【问题标题】:How to create (optionally) chainable functions like in Lodash?如何在 Lodash 中创建(可选)可链接的函数?
【发布时间】:2016-04-14 01:46:24
【问题描述】:

在 Lodash 中发现的一个常见且非常易读的模式是“链接”。使用链接,前一个函数调用的结果作为下一个函数的第一个参数传入。

例如 Lodash 文档中的这个例子:

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

// A sequence with chaining.
_(users)
  .head()
  .pick('user')
  .value();

headpick 也可以在链外使用。

查看源代码,链中调用的实际方法并没有什么特别之处——因此它必须链接到初始的_ 调用和/或value 调用。

负责人:https://github.com/lodash/lodash/blob/4.11.0/lodash.js#L6443 选择:https://github.com/lodash/lodash/blob/4.11.0/lodash.js#L12598

如何用自己的方法实现这种模式?它有术语吗?

一个例子可能是:

const house = 
    this
        .addFoundation("concrete")
        .addWalls(4)
        .addRoof(true)
        .build();

// Functions being (each can be called by manually as well)

addFoundation(house, materialType) { ... }
addWalls(house, wallCount) { ... }
addRoof(house, includeChimney) { ... }

// And..
build() // The unwrapped method to commit the above

【问题讨论】:

  • 您正在寻找_.mixin,它用于创建方法。 herethere 奇迹发生了。

标签: javascript lodash


【解决方案1】:

一个例子说明如何做到这一点

function foo(arr) {
  if (!(this instanceof foo)) {
    return new foo(arr);
  }

  this.arr = arr;
  return this;
}


foo.prototype.add = function(p) {
  this.arr.push(p);
  return this;
}

foo.prototype.print = function() {
  console.log(this.arr);
  return this;
}

foo([1, 2]).add(3).print();

说你也想这样做

foo.add(3).print();

你需要在foo(不是原型)上创建一个方法

foo.add = function(p) {
  return foo([p]);
}

foo.add(3).print() // [3]

【讨论】:

  • 抱歉,我花了一些时间来处理这个——不过我喜欢它——是有道理的。并解释了为什么在 lodash 中您需要显式调用 _.chain 并使用 .value “解包”它
【解决方案2】:

这叫做方法链。这里有两篇关于它的文章。它的基本要点是在函数末尾返回当前对象。

http://schier.co/blog/2013/11/14/method-chaining-in-javascript.html

http://javascriptissexy.com/beautiful-javascript-easily-create-chainable-cascading-methods-for-expressiveness/

【讨论】:

  • 是的,不错的文章,但我认为它只是图片的一半(纠正我我错了) - 在 Lodash 中,您可以同时调用 _.pick(object, 'x') 以及 _.(object).pick(' x') 其中前一个操作的结果作为下一个操作的第一个参数传入。在上面的文章中,涵盖了链,但不包括可选链
猜你喜欢
  • 2011-12-05
  • 1970-01-01
  • 2014-03-04
  • 2020-06-28
  • 2012-01-24
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多