How to create (optionally) chainable functions like in Lodash?

蹲街弑〆低调 提交于 2019-12-25 06:44:38

问题


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.

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 and pick can both be used outside of a chain as well.

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.

Head: https://github.com/lodash/lodash/blob/4.11.0/lodash.js#L6443 Pick: 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?

An example might be:

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

回答1:


One example on how to do it

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();

Say you want to do this as well

foo.add(3).print();

You need to create a method on foo (not the prototype)

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

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



回答2:


It's called method chaining. Here's two articles on it. The basic gist of it is that you return the current object at the end of the function.

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

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



来源:https://stackoverflow.com/questions/36612429/how-to-create-optionally-chainable-functions-like-in-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!