如何像 Lodash 一样创建(可选)可链接的函数?
How to create (optionally) chainable functions like in Lodash?
Lodash 中常见且可读性很强的模式是 "chaining"。通过链接,前一个函数调用的结果作为下一个函数调用的第一个参数传入。
例如 Lodash 文档中的示例:
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
// A sequence with chaining.
_(users)
.head()
.pick('user')
.value();
head
和 pick
也可以在链外使用。
通过源代码,在链中调用的实际方法没有明显特别之处 - 因此它必须链接到初始 _
调用 and/or 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
这叫做方法链。这是关于它的两篇文章。它的基本要点是你 return 函数末尾的当前对象。
http://schier.co/blog/2013/11/14/method-chaining-in-javascript.html
一个关于如何做的例子
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 中常见且可读性很强的模式是 "chaining"。通过链接,前一个函数调用的结果作为下一个函数调用的第一个参数传入。
例如 Lodash 文档中的示例:
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
// A sequence with chaining.
_(users)
.head()
.pick('user')
.value();
head
和 pick
也可以在链外使用。
通过源代码,在链中调用的实际方法没有明显特别之处 - 因此它必须链接到初始 _
调用 and/or 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
这叫做方法链。这是关于它的两篇文章。它的基本要点是你 return 函数末尾的当前对象。
http://schier.co/blog/2013/11/14/method-chaining-in-javascript.html
一个关于如何做的例子
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]