如何在Lodash中创建(可选)可链接函数? [英] How to create (optionally) chainable functions like in Lodash?
问题描述
在Lodash中发现的一种常见且易读的模式是链接".通过链接,上一个函数调用的结果将作为下一个的第一个参数传入.
A common, and very readable, pattern found in Lodash is "chaining". With chaining, the result of the previous function call is passed in as the first argument of the next.
例如Lodash文档中的示例:
Such as this example from Lodash docs:
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
// A sequence with chaining.
_(users)
.head()
.pick('user')
.value();
head
和pick
都可以在链外使用.
head
and pick
can both be used outside of a chain as well.
从源头开始,在链中实际调用的方法显然没有什么特别的-因此必须将其链接到初始的_
调用和/或value
调用.
Going through the source, there is nothing obviously special about the actual methods being called in the chain - so it must be linked to either the initial _
call and/or value
call.
标题: https://github.com/lodash/lodash/blob/4.11.0/lodash.js#L6443 选择: https://github.com/lodash/lodash/blob /4.11.0/lodash.js#L12598
一个人如何用自己的方法实现这种模式?并有一个术语吗?
How does one achieve this pattern with their own methods? And does it have a term?
一个例子可能是:
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
推荐答案
一个如何做的例子
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
上创建一个方法(不是原型)
You need to create a method on foo
(not the prototype)
foo.add = function(p) {
return foo([p]);
}
foo.add(3).print() // [3]
这篇关于如何在Lodash中创建(可选)可链接函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!