【发布时间】: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();
head 和pick 也可以在链外使用。
查看源代码,链中调用的实际方法并没有什么特别之处——因此它必须链接到初始的_ 调用和/或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
【问题讨论】:
标签: javascript lodash